當前位置: 首頁>>代碼示例>>Java>>正文


Java Base64.encodeBase64String方法代碼示例

本文整理匯總了Java中org.apache.commons.codec.binary.Base64.encodeBase64String方法的典型用法代碼示例。如果您正苦於以下問題:Java Base64.encodeBase64String方法的具體用法?Java Base64.encodeBase64String怎麽用?Java Base64.encodeBase64String使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.codec.binary.Base64的用法示例。


在下文中一共展示了Base64.encodeBase64String方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: SignMessage

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public static boolean SignMessage(String ellieSignature, String message, String secret) {
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
        System.out.println(hash);

        if(ellieSignature == hash){
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        System.out.println("Error");
    }
    return true;
}
 
開發者ID:EllieMae,項目名稱:api-webhook-sample-application,代碼行數:20,代碼來源:SignatureUtility.java

示例2: get

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public Document get(String url) throws Exception{
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    String user = api.getUser();String password = api.getPassword();
    String authStr = user + ":" + password;
    String authEncoded = Base64.encodeBase64String(authStr.getBytes());
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization", "Basic " + authEncoded);
    con.setDoOutput(true);
    DocumentBuilderFactory factoryBuilder = DocumentBuilderFactory.newInstance();
    factoryBuilder.setIgnoringComments(true);
    factoryBuilder.setIgnoringElementContentWhitespace(true);
    DocumentBuilder d = factoryBuilder.newDocumentBuilder();
    Document document = d.parse(con.getInputStream());
    return document;
}
 
開發者ID:CodedByYou,項目名稱:MAL-,代碼行數:17,代碼來源:MalGet.java

示例3: byteEmptyWithServiceResponseAsync

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
/**
 * Get '' as byte array.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> byteEmptyWithServiceResponseAsync() {
    final byte[] byteQuery = "".getBytes();
    String byteQueryConverted = Base64.encodeBase64String(byteQuery);
    return service.byteEmpty(byteQueryConverted)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = byteEmptyDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
 
開發者ID:Azure,項目名稱:autorest.java,代碼行數:23,代碼來源:QueriesImpl.java

示例4: testAuthenticateWithException

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
@Test
public void testAuthenticateWithException() throws Exception {
    exception = true;
    platformService.exceptionOnGetControllerSettings = new APPlatformException(
            "failed");
    Mockito.when(session.getAttribute(Matchers.eq("loggedInUserId")))
            .thenReturn(null);

    String credentials = "user1:password1";
    String credentialsEncoded = Base64
            .encodeBase64String(credentials.getBytes());

    Mockito.when(req.getHeader(Matchers.eq("Authorization")))
            .thenReturn("Basic " + credentialsEncoded);

    // And go!
    filter.doFilter(req, resp, chain);

    // Check whether request has been forwarded
    Mockito.verify(resp).setStatus(Matchers.eq(401));
    Mockito.verify(resp).setHeader(Matchers.eq("WWW-Authenticate"),
            Matchers.startsWith("Basic "));
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:24,代碼來源:AuthorizationFilterTest.java

示例5: encryptCbcTemp

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public static String encryptCbcTemp(String content, String encryptKey)
		throws EncryptException
{
	if (StringUtils.isEmpty(content) || StringUtils.isEmpty(encryptKey))
	{
		return null;
	}
	
	// 因為加密key必須為16位
	if(encryptKey.length() > 16)
	{
		encryptKey = encryptKey.substring(0, 16);
	}
	else
	{
		int padLength = 16-encryptKey.length();
		
		for(int i = 0; i < padLength ;i++)
		{
			encryptKey += '0';
		}
	}
	
	try
	{
		IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(content.getBytes("utf-8"));

		return Base64.encodeBase64String(encryptedData);
	}
	catch (Exception e)
	{
		throw new EncryptException("Failed to encrypt for content: "
				+ content + ", encrypt key: " + encryptKey, e);
	}

}
 
開發者ID:marlonwang,項目名稱:raven,代碼行數:41,代碼來源:AESUtils.java

示例6: testbrokenLink

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);

    String url = "http://localhost:8080/sjk-market/market/brokenLink.d";
    url = "http://app-t.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", encodeBase64);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
 
開發者ID:zhaoxi1988,項目名稱:sjk,代碼行數:35,代碼來源:ControllerTest.java

示例7: compress

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public static String compress(String stringToCompress) throws UnsupportedEncodingException
{
    byte[] compressedData = new byte[1024];
    byte[] stringAsBytes = stringToCompress.getBytes("UTF-8");

    Deflater compressor = new Deflater();
    compressor.setInput(stringAsBytes);
    compressor.finish();
    int compressedDataLength = compressor.deflate(compressedData);

    byte[] bytes = Arrays.copyOf(compressedData, compressedDataLength);
    return Base64.encodeBase64String(bytes);
}
 
開發者ID:tmobile,項目名稱:keybiner,代碼行數:14,代碼來源:Compression.java

示例8: testCreateInstanceUserData

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
@Test
public void testCreateInstanceUserData() throws Exception {
    String userData = "line1\nline2\n";
    String userDataBase64 = Base64.encodeBase64String(userData.getBytes());
    File myFile = createUserDataFile(userData);
    try {
        URL fileUrl = myFile.toURI().toURL();
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, fileUrl.toString()));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");

        ec2comm.createInstance(image);
        String result = ph.getAWSInstanceId();
        assertEquals("instance2", result);
        ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
                .forClass(RunInstancesRequest.class);
        verify(ec2).runInstances(arg1.capture());
        RunInstancesRequest rir = arg1.getValue();
        assertEquals(userDataBase64, rir.getUserData());
    } finally {
        myFile.delete();
    }
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:30,代碼來源:EC2CommunicationTest.java

示例9: main

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public static void main(String[] args) throws UnsupportedEncodingException {
	String encodeString = URLEncoder.encode("何劍","UTF-8");
	System.out.println("encode : " + encodeString);
	System.out.println("decode : " + URLDecoder.decode(encodeString, "UTF-8"));
	encodeString = Base64.encodeBase64String("何劍".getBytes());
	System.out.println(encodeString);
	System.out.println(new String(Base64.decodeBase64(encodeString),"UTF-8"));
	
	String str = "aHR0cDovL3BtZi5jaGV4aWFuZy5jb20vdGVzdC9hdXRoLmh0bQ====";
	str = str.substring(0, str.length() - 2);
	System.out.println(new String(Base64.decodeBase64(str),"UTF-8"));
	
}
 
開發者ID:tojaoomy,項目名稱:private-WeChat,代碼行數:14,代碼來源:AuthorizationController.java

示例10: testbrokenLink

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    String test = "eyJjb3VudCI6IDEwLCAibWFya2V0TmFtZSI6ICJBcHBDaGluYSIsICJkYXRhIjogW3sibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmdvb2dsZS5hbmRyb2lkLmFwcHMubWFwcyIsICJpZCI6IDEsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20ud2VhdGhlci5XZWF0aGVyIiwgImlkIjogMiwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5zdHlsZW0ud2FsbHBhcGVycyIsICJpZCI6IDQsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20uc2hhemFtLmVuY29yZS5hbmRyb2lkIiwgImlkIjogNSwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5yaW5nZHJvaWQiLCAiaWQiOiA2LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLnAxLmNob21wc21zIiwgImlkIjogNywgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5oYW5kY2VudC5uZXh0c21zIiwgImlkIjogOCwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5mYWNlYm9vay5rYXRhbmEiLCAiaWQiOiA5LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmNvZGUuaS5tdXNpYyIsICJpZCI6IDEwLCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmJpZ2d1LnNob3BzYXZ2eSIsICJpZCI6IDExLCAic3RhdHVzQ29kZSI6IDQwNH1dLCAia2V5IjogImpqRzhMa0MzTUh5RjlYY3NWS2g2Rkh4bXRMQ05ZdE14In0=";
    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);
    System.out.println(encodeBase64);

    String url = "http://localhost:9080/sjk-market-admin/market/brokenLink.d";
    url = "http://app.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", test);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
 
開發者ID:zhaoxi1988,項目名稱:sjk,代碼行數:37,代碼來源:ControllerTest.java

示例11: encryptPassword

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
/**
 * Returns encrypted version of given password like algorithm like in
 * WS-UsernameToken
 * 
 * @throws NoSuchAlgorithmException
 */
public String encryptPassword() throws NoSuchAlgorithmException {
	String nonce = getNonce();
	String timestamp = getUTCTime();

	String beforeEncryption = nonce + timestamp + password;

	byte[] encryptedRaw;
	encryptedRaw = sha1(beforeEncryption);
	String encoded = Base64.encodeBase64String(encryptedRaw);
	return encoded;
}
 
開發者ID:D2Edev,項目名稱:onvifjava,代碼行數:18,代碼來源:OnvifDevice.java

示例12: generateEncodedKey

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
public String generateEncodedKey()
  {
try
{
   	return Base64.encodeBase64String(generateKeyData());
}
catch(Throwable e)
{
	fail("Unexpected exception: " + e.getMessage());
	return null;
}
  }
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:13,代碼來源:KeyStoreTests.java

示例13: getEncoded

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
String getEncoded(String val) {
    return Base64.encodeBase64String(val.getBytes());
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:4,代碼來源:SettingsUI.java

示例14: makeDocument

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
@Override
public void makeDocument(byte[] httpData) throws Exception {
       String t = context.statistics.start(EngineStatistics.GENERATE_DOM);

       try {
       	String stringData = "";
       	
       	if (httpData == null || httpData.length == 0) {
       		// nothing to do
       	}
       	else if (dataEncoding == HTTP_DATA_ENCODING_STRING) {
       		String charset = dataStringCharset;
       		
       		if (StringUtils.isBlank(charset)) {
       			charset  = ((HttpConnector) parent).getCharset();
       			Engine.logBeans.debug("(HttpTransaction) 'HTTP string charset' is blank, use detected charset: " + charset);
       		}
       		
           	if (charset == null) {
           		charset = "ascii";
           		Engine.logBeans.info("(HttpTransaction) No valid charset defined, use basic charset: " + charset);
           	}
           	try {
           		stringData = new String(httpData, charset);
           	} catch (UnsupportedEncodingException e) {
           		Engine.logBeans.warn("(HttpTransaction) Unsupported Encoding to decode the response, use ascii instead",  e);
           		stringData = new String(httpData, "ascii");
           	}
       	}
       	else if (dataEncoding == HTTP_DATA_ENCODING_BASE64) {
       		stringData = Base64.encodeBase64String(httpData);
       	}
       	else {
       		throw new IllegalArgumentException("Unknown data encoding: " + dataEncoding);
       	}
   		
       	Node child = responseInCDATA ?
       		context.outputDocument.createCDATASection(stringData) // remove TextCodec.UTF8Encode for #453
       		: context.outputDocument.createTextNode(stringData);
       	
       	Element outputDocumentRootElement = context.outputDocument.getDocumentElement();
       	outputDocumentRootElement.appendChild(child);
       }
       finally {
   		context.statistics.stop(t);
       }
   }
 
開發者ID:convertigo,項目名稱:convertigo-engine,代碼行數:48,代碼來源:HttpTransaction.java

示例15: base64ClientIdSecret

import org.apache.commons.codec.binary.Base64; //導入方法依賴的package包/類
private String base64ClientIdSecret() {
    String clientIdSecret = new StringJoiner(":")
            .add(oAuth2ClientProperties.getClientId())
            .add(oAuth2ClientProperties.getClientSecret()).toString();
    return Base64.encodeBase64String(clientIdSecret.getBytes());
}
 
開發者ID:SopraSteriaGroup,項目名稱:initiatives_backend_auth,代碼行數:7,代碼來源:TokenService.java


注:本文中的org.apache.commons.codec.binary.Base64.encodeBase64String方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。