Java Code Examples for org.apache.commons.codec.binary.Base64#encode()

The following examples show how to use org.apache.commons.codec.binary.Base64#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: DalBase64.java    From das with Apache License 2.0 6 votes vote down vote up
public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe,
        final int maxResultSize) {
    if (binaryData == null || binaryData.length == 0) {
        return binaryData;
    }

    // Create this so can use the super-class method
    // Also ensures that the same roundings are performed by the ctor and the code
    final Base64 b64 = isChunked ? new DalBase64(urlSafe) : new DalBase64(0, CHUNK_SEPARATOR, urlSafe);
    final long len = b64.getEncodedLength(binaryData);
    if (len > maxResultSize) {
        throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len
                + ") than the specified maximum size of " + maxResultSize);
    }

    return b64.encode(binaryData);
}
 
Example 2
Source File: BpmnaiUtils.java    From bpmn.ai with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String md5CecksumOfObject(Object obj) throws IOException, NoSuchAlgorithmException {
    if (obj == null) {
        return "";
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.close();

    MessageDigest m = MessageDigest.getInstance("MD5");
    m.update(baos.toByteArray());

    Base64 codec = new Base64();
    byte[] encoded = codec.encode(m.digest());

    return DigestUtils.md5Hex(new String(encoded)).toUpperCase();
}
 
Example 3
Source File: DigitalSignature.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String ProgMain(Element Document){
	try{
         
             System.out.println("Beginning of XmlSignature:");
             //Call the function to sign the document
             byte[] signeddata = SignedData(Document).getEncoded();
    if (signeddata == null || signeddata.length == 0) return null;
             else
             {
             System.out.println("End of Xml Signature");
	  	  	
             // Convert the signed data in a BASE64 string to make it a valid content 
             // for Yawl
             Base64 enCoder = new Base64();
             String base64OfSignatureValue = new String(enCoder.encode(signeddata));
             System.out.println(base64OfSignatureValue);

             return base64OfSignatureValue;
           }

            
	} catch (Exception e) {e.printStackTrace();
	return null;
	}
}
 
Example 4
Source File: Uploader.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 接受并保存以base64格式上传的文件
 * 
 * @param fieldName
 */
public void uploadBase64(String fieldName) {
	String savePath = this.getFolder(this.savePath);
	String base64Data = this.request.getParameter(fieldName);
	this.fileName = this.getName("test.png");
	this.url = savePath + "/" + this.fileName;
	Base64 decoder=new Base64();  

	try {
		File outFile = new File(this.getPhysicalPath(this.url));
		OutputStream ro = new FileOutputStream(outFile);
		byte[] b = decoder.encode(base64Data.getBytes());
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {
				b[i] += 256;
			}
		}
		ro.write(b);
		ro.flush();
		ro.close();
		this.state = this.errorInfo.get("SUCCESS");
	} catch (Exception e) {
		this.state = this.errorInfo.get("IO");
	}
}
 
Example 5
Source File: Sign.java    From api-gateway-demo-sign-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * 先进行MD5摘要再进行Base64编码获取摘要字符串
 *
 * @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");
    }
}
 
Example 6
Source File: MessageDigestUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * 先进行MD5摘要再进行Base64编码获取摘要字符串
 *
 * @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();
        final byte[] enbytes = base64.encode(md.digest());
        return new String(enbytes);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("unknown algorithm MD5");
    }
}
 
Example 7
Source File: DalBase64.java    From dal with Apache License 2.0 6 votes vote down vote up
public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe,
        final int maxResultSize) {
    if (binaryData == null || binaryData.length == 0) {
        return binaryData;
    }

    // Create this so can use the super-class method
    // Also ensures that the same roundings are performed by the ctor and the code
    final Base64 b64 = isChunked ? new DalBase64(urlSafe) : new DalBase64(0, CHUNK_SEPARATOR, urlSafe);
    final long len = b64.getEncodedLength(binaryData);
    if (len > maxResultSize) {
        throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len
                + ") than the specified maximum size of " + maxResultSize);
    }

    return b64.encode(binaryData);
}
 
Example 8
Source File: ApacheCommonsEncodeDecodeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenStringIsEncoded() throws UnsupportedEncodingException {
    final String originalInput = "test input";
    final Base64 base64 = new Base64();
    final String encodedString = new String(base64.encode(originalInput.getBytes()));

    assertNotNull(encodedString);
    assertNotEquals(originalInput, encodedString);
}
 
Example 9
Source File: BasicComponent.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private void writeImages( )
{
	for ( String uri : imageSrc )
	{
		String imageType = uri.substring( uri.indexOf( '.' ) + 1 );
		mhtPartWriter.println( );
		mhtPartWriter.println( "--" + BOUNDARY );
		mhtPartWriter.println( "Content-Type: image/" + imageType );
		mhtPartWriter.println( "Content-Transfer-Encoding: base64" );
		mhtPartWriter.println( "Content-Location:" + uri );
		mhtPartWriter.println( );

		try
		{
			byte[] data = EmitterUtil.getImageData( uri );
			if ( data != null && data.length != 0 )
			{
				Base64 base = new Base64( );
				String pic2Text = new String( base.encode( data ) );
				mhtPartWriter.println( pic2Text );
			}
		}
		catch ( IOException e )
		{
			logger.log( Level.WARNING, e.getLocalizedMessage( ) );
		}
	}
	mhtPartWriter.println( );
	mhtPartWriter.println( "--" + BOUNDARY + "--" );
}
 
Example 10
Source File: AbstractOdfWriter.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void drawImageData( byte[] data )
{
	String pic2Text = null;
	if ( data != null && data.length != 0 )
	{
		Base64 base = new Base64( );
		pic2Text = new String( base.encode( data ) );
	}
	if ( pic2Text != null )
	{
		writer.openTag( "office:binary-data" );
		writer.text( pic2Text );
		writer.closeTag( "office:binary-data" );
	}
}
 
Example 11
Source File: AmazonSignedRequestsHelper.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Compute the HMAC.
 *  
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64();
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}
 
Example 12
Source File: HttpRequestsTest.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Test
public void customHeaderAuth() throws Exception {

    CouchConfig customCouchConfig = getCouchConfig(testDb);

    // check that we are running in a configuration where there is no username/password set:
    // (most commonly this would be the default config of running against a local couch instance
    // in admin party mode)
    org.junit.Assume.assumeTrue("Test skipped because Basic Auth credentials are required to " +
                    "access this server",
            TestOptions.COOKIE_AUTH && Misc.isStringNullOrEmpty(customCouchConfig.getRootUri().getUserInfo()));

    try {
        String authString = "foo:bar";
        Base64 base64 = new Base64();
        String authHeaderValue = "Basic " + new String(base64.encode(authString.getBytes()));
        ArrayList<HttpConnectionRequestInterceptor> customInterceptors = new ArrayList<HttpConnectionRequestInterceptor>();
        customInterceptors.add(makeHeaderInterceptor("Authorization", authHeaderValue));
        customCouchConfig.setRequestInterceptors(customInterceptors);
        CouchClient customClient = new CouchClient(customCouchConfig.getRootUri(),
                customCouchConfig.getRequestInterceptors(),
                customCouchConfig.getResponseInterceptors());
        customClient.getDbInfo();
        Assert.fail("Expected CouchException to be thrown");
    } catch (CouchException ce) {
        Assert.assertEquals("unauthorized", ce.getError());
    }
}
 
Example 13
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected static String convertToPem(Certificate cert) throws CertificateEncodingException {
    Base64 encoder = new Base64(64);
    String cert_begin = "-----BEGIN CERTIFICATE-----\n";
    String end_cert = "-----END CERTIFICATE-----";

    byte[] derCert = cert.getEncoded();
    String pemCertPre = new String(encoder.encode(derCert), Charset.defaultCharset());
    String pemCert = cert_begin + pemCertPre + end_cert;
    return pemCert;
}
 
Example 14
Source File: GoogleAccountsServiceTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
protected static String encodeMessage(final String xmlString) throws IOException {
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(
            byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();

    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream
            .toByteArray());
    return new String(base64EncodedByteArray);
}
 
Example 15
Source File: CrucibleSessionImpl.java    From Crucible4IDEA with MIT License 5 votes vote down vote up
public static String encode(String str2encode) {
  try {
    Base64 base64 = new Base64();
    byte[] bytes = base64.encode(str2encode.getBytes("UTF-8"));
    return new String(bytes);
  } catch (UnsupportedEncodingException e) {
    throw new RuntimeException("UTF-8 is not supported", e);
  }
}
 
Example 16
Source File: ApacheCommonsEncodeDecodeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
    final String originalInput = "test input";
    final Base64 base64 = new Base64();
    final String encodedString = new String(base64.encode(originalInput.getBytes()));

    final String decodedString = new String(base64.decode(encodedString.getBytes()));

    assertNotNull(decodedString);
    assertEquals(originalInput, decodedString);
}
 
Example 17
Source File: SamlFederationResource.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private String fetchCertificateText(KeyStore.PrivateKeyEntry keystoreEntry) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    X509Certificate certificate = (X509Certificate) keystoreEntry.getCertificate();

    Base64 encoder = new Base64(64);
    String certificateText = new String(encoder.encode(certificate.getEncoded()));

    return certificateText;
}
 
Example 18
Source File: Base64Encoder.java    From nem.core with MIT License 2 votes vote down vote up
/**
 * Converts a byte array to a Base64 string.
 *
 * @param bytes The input byte array.
 * @return The output Base64 string.
 */
public static String getString(final byte[] bytes) {
	final Base64 codec = new Base64();
	final byte[] decodedBytes = codec.encode(bytes);
	return StringEncoder.getString(decodedBytes);
}
 
Example 19
Source File: Base64Encoder.java    From symbol-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a byte array to a Base64 string.
 *
 * @param bytes The input byte array.
 * @return The output Base64 string.
 */
public static String getString(final byte[] bytes) {
    final Base64 codec = new Base64();
    final byte[] decodedBytes = codec.encode(bytes);
    return StringEncoder.getString(decodedBytes);
}
 
Example 20
Source File: MyTools.java    From springBoot-study with Apache License 2.0 2 votes vote down vote up
/**
 * base64 加密
 * 
 * @param str
 * @return
 */
public static String base64EnStr(String str) {
	Base64 base64 = new Base64();
	byte[] encode = base64.encode(str.getBytes());
	return new String(encode);
}