本文整理了Java中net.iharder.Base64
类的一些代码示例,展示了Base64
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Base64
类的具体详情如下:
包路径:net.iharder.Base64
类名称:Base64
[英]Encodes and decodes to and from Base64 notation.
Homepage: http://iharder.net/base64.
Example:String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );
The options parameter, which appears in a few places, is used to pass several pieces of information to the encoder. In the "higher level" methods such as encodeBytes( bytes, options ) the options parameter can be used to indicate such things as first gzipping the bytes before encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered dialects.
Note, according to RFC3548, Section 2.1, implementations should not add line feeds unless explicitly told to do so. I've got Base64 set to this behavior now, although earlier versions broke lines by default.
The constants defined in Base64 can be OR-ed together to combine options, so you might make a call like this:String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );
to compress the data before encoding it and then making the output have newline characters.
Also...String encoded = Base64.encodeBytes( crazyString.getBytes() );
Change Log:
v2.3.7 - Fixed subtle bug when base 64 input stream contained the value 01111111, which is an invalid base 64 character but should not throw an ArrayIndexOutOfBoundsException either. Led to discovery of mishandling (or potential for better handling) of other bad input characters. You should now get an IOException if you try decoding something that has bad characters in it.
v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded string ended in the last column; the buffer was not properly shrunk and contained an extra (null) byte that made it into the string.
v2.3.5 - Fixed bug in #encodeFromFile where estimated buffer size was wrong for files of size 31, 34, and 37 bytes.
v2.3.4 - Fixed bug when working with gzipped streams whereby flushing the Base64.OutputStream closed the Base64 encoding (by padding with equals signs) too soon. Also added an option to suppress the automatic decoding of gzipped streams. Also added experimental support for specifying a class loader when using the #decodeToObject(java.lang.String,int,java.lang.ClassLoader)method.
v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java footprint with its CharEncoders and so forth. Fixed some javadocs that were inconsistent. Removed imports and specified things like java.io.IOException explicitly inline.
v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the final encoded data will be so that the code doesn't have to create two output arrays: an oversized initial one and then a final, exact-sized one. Big win when using the #encodeBytesToBytes(byte[]) family of methods (and not using the gzip options which uses a different mechanism with streams and stuff).
v2.3.1 - Added #encodeBytesToBytes(byte[],int,int,int) and some similar helper methods to be more efficient with memory by not returning a String but just a byte array.
v2.3 - This is not a drop-in replacement! This is two years of comments and bug fixes queued up and finally executed. Thanks to everyone who sent me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. Much bad coding was cleaned up including throwing exceptions where necessary instead of returning null values or something similar. Here are some changes that may affect you:
Does not break lines, by default. This is to keep in compliance with RFC3548.
v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug when using very small files (~<40 bytes).
v2.2 - Added some helper methods for encoding/decoding directly from one file to the next. Also added a main() method to support command line encoding/decoding from one file to the next. Also added these Base64 dialects:
The default is RFC3548 format.
v2.1 - Cleaned up javadoc comments and unused variables and methods. Added some convenience methods for reading and writing to and from files.
v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems with other encodings (like EBCDIC).
v2.0.1 - Fixed an error when decoding a single byte, that is, when the encoded data was a single byte.
v2.0 - I got rid of methods that used booleans to set options. Now everything is more consolidated and cleaner. The code now detects when data that's being decoded is gzip-compressed and will decompress it automatically. Generally things are cleaner. You'll probably have to change some method calls that you were making to support the new options format (ints that you "OR" together).
v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using decode( String s, boolean gzipCompressed ). Added the ability to "suspend" encoding in the Output Stream so you can turn on and off the encoding if you need to embed base64 data in an otherwise "normal" stream (like an XML file).
v1.5 - Output stream pases on flush() command but doesn't do anything itself. This helps when using GZIP streams. Added the ability to GZip-compress objects before encoding them.
v1.4 - Added helper methods to read/write files.
v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream where last buffer being read, if not completely full, was not returned.
v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.
v1.3.3 - Fixed I/O streams which were totally messed up.
I am placing this code in the Public Domain. Do with it as you will. This software comes with no guarantees or warranties but with plenty of well-wishing instead! Please visit http://iharder.net/base64 periodically to check for updates or to contribute improvements.
[中]对Base64符号进行编码和解码。
主页:http://iharder.net/base64。
例子:String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );
选项参数出现在几个地方,用于将多条信息传递给编码器。在encodeBytes(bytes,options)等“更高级别”方法中,options参数可用于指示在编码字节之前先压缩字节,不插入换行符,以及使用URL安全和有序方言进行编码。
注意,根据RFC3548,第2.1节,除非明确要求添加换行符,否则实现不应该添加换行符。我现在已经将Base64设置为这种行为,尽管早期版本在默认情况下会中断。
Base64中定义的常量可以合并或合并在一起以组合选项,因此您可以进行如下调用:String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );
在编码数据之前压缩数据,然后使输出具有换行符。
而且String encoded = Base64.encodeBytes( crazyString.getBytes() );
更改日志:
*v2。3.7-修复了Base64输入流包含值01111111时的细微错误,该值是无效的Base64字符,但也不应引发ArrayIndexOutOfBoundsException。导致发现错误处理(或可能更好地处理)其他错误输入字符。如果您尝试解码包含坏字符的内容,现在应该会得到一个IOException。
*v2。3.6-修复了断行时的错误,编码字符串的最后一个字节在最后一列结束;缓冲区未正确收缩,并包含一个额外的(空)字节,使其进入字符串。
*v2。3.5-修复了#encodeFromFile中的错误,其中大小为31、34和37字节的文件的估计缓冲区大小错误。
*v2。3.4-修复了处理Gzip流时刷新Base64的错误。OutputStream过早地关闭了Base64编码(通过使用等号填充)。还添加了一个选项来抑制gzip流的自动解码。还添加了在使用#decodeToObject(java.lang.String,int,java.lang.ClassLoader)方法时指定类加载器的实验支持。
*v2。3.3-将默认字符编码更改为US-ASCII,从而减少了其字符编码器的内部Java占用空间,等等。修复了一些不一致的Javadoc。删除了导入和指定的东西,如java。木卫一。IOException显式内联。
*v2。3.2-减少内存占用!最后,对最终编码数据的大小进行了“猜测”,这样代码就不必创建两个输出数组:一个超大的初始数组和一个最终的、精确大小的数组。当使用#encodeBytesToBytes(byte[])方法家族(而不使用gzip选项,它使用不同的机制处理流和内容)时,这是一个巨大的胜利。
*v2。3.1-添加了#encodeBytesToBytes(byte[],int,int,int,int)和一些类似的助手方法,通过不返回字符串而只返回字节数组来提高内存效率。
*v2。3-这不是一个一次性的替代品!这是长达两年的评论和bug修复排队并最终执行。感谢所有给我发邮件的人,很抱歉我没能把你的补丁分发给其他人。许多糟糕的编码都被清除了,包括在必要时抛出异常,而不是返回空值或类似的东西。以下是一些可能会影响您的更改:
**默认情况下不断线。*这是为了遵守RFC3548。
**抛出异常而不是返回空值。*因为一些操作(特别是那些允许GZIP选项的操作)使用IO流,所以有可能使用java。木卫一。正在抛出异常。经过一些讨论和思考,我已经改变了方法的行为来抛出java。木卫一。IOExceptions,而不是在出现错误时返回null。我认为这更合适,尽管它需要对代码进行一些更改。对不起,一开始就应该这样做。
**删除对系统的所有引用。退出,系统。呃,等等。*我真丢脸。我所能说的就是他们曾经在那里。
*根据需要抛出NullPointerException和IllegalArgumentException,例如当传递的数组为null或偏移量无效时。
*清理尽可能多的javadoc以避免任何javadoc警告。对于那些在自己的项目中做得很透彻,然后在这个文件上有大量javadoc警告的人来说,这尤其令人讨厌。
*v2。2.1-修复了使用URL_安全和有序编码的错误。修复了使用非常小的文件(~<40字节)时的错误。
1.v2。2-添加了一些辅助方法,用于直接从一个文件到下一个文件进行编码/解码。还添加了main()方法以支持从一个文件到下一个文件的命令行编码/解码。还添加了以下64种基本方言:
1.默认为RFC3548格式。
1.呼叫Base64。setFormat(Base64.Base64_FORMAT.URLSAFE_FORMAT)生成URL和文件名友好格式,如RFC3548第4节所述。http://www.faqs.org/rfcs/rfc3548.html
1.呼叫Base64。setFormat(Base64.Base64\u FORMAT.ORDERED\u FORMAT)生成URL和文件名友好格式,该格式保留词汇顺序,如中所述http://www.faqs.org/qa/rfcc-1940.html
特别感谢{http://www.powerset.com/的吉姆·凯勒曼为新的Base64方言所作的贡献。
1.v2。1-清理了javadoc注释和未使用的变量和方法。添加了一些方便的文件读写方法。
1.v2。0.2-现在在使用其他编码(如EBCDIC)的系统上代码失败的地方指定UTF-8编码。
1.v2。0.1-修复了解码单个字节时的错误,即编码数据为单个字节时的错误。
1.v2。0-我去掉了使用布尔设置选项的方法。现在一切都更加巩固和清洁。代码现在检测正在解码的数据何时被压缩并将自动解压缩。一般来说,情况比较干净。您可能必须更改正在进行的一些方法调用,以支持新的选项格式(您“或”一起使用的int)。
1.v1。5.1-修复了使用decode(字符串s,布尔gzipCompressed)对字节[]进行解压缩和解码时出现的错误。添加了在输出流中“挂起”编码的功能,因此,如果需要在其他“正常”流(如XML文件)中嵌入base64数据,则可以打开和关闭编码。
1.v1。5-输出流在flush()命令上运行,但本身不执行任何操作。这有助于使用GZIP流。添加了在编码对象之前压缩对象的能力。
1.v1。4-添加了用于读取/写入文件的帮助器方法。
1.v1。3.6-固定输出流。刷新(),以便重置“位置”。
1.v1。3.5-添加了用于打开和关闭换行符的标志。修复了输入流中最后一个被读取的缓冲区(若未完全填满)未返回的错误。
1.v1。3.4-修复了在错误时间抛出“未正确填充的流”错误。
1.v1。3.3-修复了完全混乱的I/O流。
我将此代码置于公共域中。你想怎么做就怎么做。这个软件没有任何保证或保证,但却有很多美好的愿望!请定期访问http://iharder.net/base64,检查更新或作出改进。
代码示例来源:origin: igniterealtime/Smack
@Override
public String encodeToString(byte[] input, int offset, int len) {
return Base64.encodeBytes(input, offset, len);
}
代码示例来源:origin: igniterealtime/Smack
@Override
public byte[] decode(byte[] input, int offset, int len) {
try {
return Base64.decode(input, offset, len, 0);
}
catch (IllegalArgumentException e) {
// Expected by e.g. the unit test.
// " Base64-encoded string must have at least four characters, but length specified was 1",
// should not cause an exception, but instead null should be returned. Maybe
// this should be changed in a later Smack release, so that the actual exception
// is handled.
return null;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public String generateSdk(SdkProfileDto sdkProfile, SdkPlatform targetPlatform)
throws KaaAdminServiceException {
try {
doGenerateSdk(sdkProfile, targetPlatform);
return Base64.encodeObject(
new CacheService.SdkKey(sdkProfile, targetPlatform), Base64.URL_SAFE);
} catch (Exception ex) {
throw Utils.handleException(ex);
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String recordKeyBase64 = URLDecoder.decode(request.getParameter(RECORD_KEY_PARAMETER), "UTF-8");
try {
RecordKey key = (RecordKey) Base64.decodeToObject(recordKeyBase64, Base64.URL_SAFE, null);
FileData recordLibrary = cacheService.getRecordData(key);
ServletUtils.prepareDisposition(request, response, recordLibrary.getFileName());
response.setContentLength(recordLibrary.getFileData().length);
response.setBufferSize(BUFFER);
response.getOutputStream().write(recordLibrary.getFileData());
response.flushBuffer();
} catch (Exception ex) {
LOG.error("Unexpected error in RecordLibraryServlet.doGet: ", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get file: "
+ ex.getMessage());
}
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sdkKeyBase64 = URLDecoder.decode(request.getParameter(SDK_KEY_PARAMETER), "UTF-8");
try {
CacheService.SdkKey key = (CacheService.SdkKey) Base64
.decodeToObject(sdkKeyBase64, Base64.URL_SAFE, null);
FileData sdkFile = cacheService.getSdk(key);
response.setContentType(sdkFile.getContentType());
ServletUtils.prepareDisposition(request, response, sdkFile.getFileName());
response.setContentLength(sdkFile.getFileData().length);
response.setBufferSize(BUFFER);
response.getOutputStream().write(sdkFile.getFileData());
response.flushBuffer();
} catch (Exception ex) {
LOG.error("Unexpected error in SdkServlet.doGet: ", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get Sdk file: "
+ ex.getMessage());
}
}
代码示例来源:origin: briandilley/jsonrpc4j
@Test
public void testGetMethod_base64Params() throws Exception {
EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
EasyMock.replay(mockService);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
MockHttpServletResponse respOnse= new MockHttpServletResponse();
request.addParameter("id", Integer.toString(123));
request.addParameter("method", "testMethod");
request.addParameter("params", net.iharder.Base64.encodeBytes("[\"Whir?inaki\"]".getBytes(StandardCharsets.UTF_8)));
jsonRpcServer.handle(request, response);
assertTrue("application/json-rpc".equals(response.getContentType()));
checkSuccessfulResponse(response);
}
代码示例来源:origin: igniterealtime/Smack
@Override
public byte[] decode(String string) {
try {
return Base64.decode(string);
}
catch (IllegalArgumentException e) {
// Expected by e.g. the unit test.
// " Base64-encoded string must have at least four characters, but length specified was 1",
// should not cause an exception, but instead null should be returned. Maybe
// this should be changed in a later Smack release, so that the actual exception
// is handled.
return null;
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public String getRecordDataByApplicationIdAndSchemaVersion(String applicationId,
int schemaVersion,
RecordKey.RecordFiles file)
throws KaaAdminServiceException {
checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
try {
checkApplicationId(applicationId);
RecordKey sdkKey = new RecordKey(applicationId, schemaVersion, file);
return Base64.encodeObject(sdkKey, Base64.URL_SAFE);
} catch (Exception ex) {
throw Utils.handleException(ex);
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ctlExportKeyBase64 = URLDecoder
.decode(request.getParameter(CTL_EXPORT_KEY_PARAMETER), "UTF-8");
try {
CtlSchemaExportKey key = (CtlSchemaExportKey) Base64
.decodeToObject(ctlExportKeyBase64, Base64.URL_SAFE, null);
FileData ctlExportData = cacheService.getExportedCtlSchema(key);
ServletUtils.prepareDisposition(request, response, ctlExportData.getFileName());
response.setContentType(ctlExportData.getContentType());
response.setContentLength(ctlExportData.getFileData().length);
response.setBufferSize(BUFFER);
response.getOutputStream().write(ctlExportData.getFileData());
response.flushBuffer();
} catch (Exception ex) {
LOG.error("Unexpected error in CtlExportServlet.doGet: ", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get file: "
+ ex.getMessage());
}
}
}
代码示例来源:origin: uk.org.mygrid.taverna/taverna-contrib
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* @param source
* The data to convert
* @since 1.4
*/
public static String encodeBytes(byte[] source) {
return encodeBytes(source, 0, source.length, NO_OPTIONS);
} // end encodeBytes
代码示例来源:origin: kaaproject/kaa
@Override
public EndpointNotificationDto sendUnicastNotification(NotificationDto notification,
String clientKeyHash,
byte[] body)
throws KaaAdminServiceException {
checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
try {
checkExpiredDate(notification);
notification.setBody(body);
checkApplicationId(notification.getApplicationId());
TopicDto topic = controlService.getTopic(notification.getTopicId());
Utils.checkNotNull(topic);
checkApplicationId(topic.getApplicationId());
EndpointNotificationDto unicastNotification = new EndpointNotificationDto();
unicastNotification.setEndpointKeyHash(
Base64.decode(clientKeyHash.getBytes(Charsets.UTF_8)));
unicastNotification.setNotificationDto(notification);
return controlService.editUnicastNotification(unicastNotification);
} catch (Exception ex) {
throw Utils.handleException(ex);
}
}
代码示例来源:origin: kaaproject/kaa
@Override
public String getRecordLibraryByApplicationIdAndSchemaVersion(String applicationId,
int logSchemaVersion,
RecordKey.RecordFiles file)
throws KaaAdminServiceException {
checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
try {
checkApplicationId(applicationId);
RecordKey sdkKey = new RecordKey(applicationId, logSchemaVersion, file);
return Base64.encodeObject(sdkKey, Base64.URL_SAFE);
} catch (Exception ex) {
throw Utils.handleException(ex);
}
}
代码示例来源:origin: Nextdoor/bender
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns null if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
代码示例来源:origin: pwm-project/pwm
public static String base64Encode( final byte[] input )
{
return Base64.encodeBytes( input );
}
代码示例来源:origin: briandilley/jsonrpc4j
decodedParams = new String(Base64.decode(params), StandardCharsets.UTF_8);
} else {
switch (params.charAt(0)) {
代码示例来源:origin: kaaproject/kaa
@Override
public String prepareCtlSchemaExport(String ctlSchemaId,
CTLSchemaExportMethod method)
throws KaaAdminServiceException {
checkAuthority(KaaAuthorityDto.values());
try {
CTLSchemaDto schemaFound = controlService.getCtlSchemaById(ctlSchemaId);
Utils.checkNotNull(schemaFound);
checkCtlSchemaReadScope(
schemaFound.getMetaInfo().getTenantId(), schemaFound.getMetaInfo().getApplicationId());
CtlSchemaExportKey key = new CtlSchemaExportKey(ctlSchemaId, method);
return Base64.encodeObject(key, Base64.URL_SAFE);
} catch (Exception ex) {
throw Utils.handleException(ex);
}
}
代码示例来源:origin: pelotoncycle/weberknecht
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns null if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
代码示例来源:origin: pwm-project/pwm
public static String base64Encode( final byte[] input, final StringUtil.Base64Options... options )
throws IOException
{
final int b64UtilOptiOns= Base64Options.asBase64UtilOptions( options );
if ( b64UtilOptions > 0 )
{
return Base64.encodeBytes( input, b64UtilOptions );
}
else
{
return Base64.encodeBytes( input );
}
}
代码示例来源:origin: pwm-project/pwm
public static byte[] base64Decode( final String input )
throws IOException
{
return Base64.decode( input );
}
代码示例来源:origin: uk.org.mygrid.taverna/taverna-contrib
/**
* Serializes an object and returns the Base64-encoded version of that
* serialized object. If the object cannot be serialized or there is another
* error, the method will return null. The object is not
* GZip-compressed before being encoded.
*
* @param serializableObject
* The object to encode
* @return The Base64-encoded object
* @since 1.4
*/
public static String encodeObject(java.io.Serializable serializableObject) {
return encodeObject(serializableObject, NO_OPTIONS);
} // end encodeObject