下面列出了 org.apache.commons.codec.binary.Base64 # encode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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();
}
/**
* 先进行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");
}
}
/**
* 先进行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");
}
}
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);
}
/**
* 接受并保存以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");
}
}
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;
}
}
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;
}
@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);
}
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);
}
}
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);
}
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;
}
@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());
}
}
/**
* 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;
}
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" );
}
}
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 + "--" );
}
@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);
}
/**
* base64 加密
*
* @param str
* @return
*/
public static String base64EnStr(String str) {
Base64 base64 = new Base64();
byte[] encode = base64.encode(str.getBytes());
return new String(encode);
}
/**
* 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);
}
/**
* 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);
}