Java / Groovy中的Base64编码

35

在Java中,将byte[]转换为Base64字符串的正确方法是什么?更好的方法是使用Grails / Groovy,因为它告诉我encodeAsBase64()函数已被弃用。不建议使用sun.misc.BASE64Encoder包,并且在某些Windows平台上输出的字符串大小不同。

5个回答

111

在Groovy中首选的方法是:

 def encoded = "Hello World".bytes.encodeBase64().toString()
 assert encoded == "SGVsbG8gV29ybGQ="
 def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
 assert decoded == "Hello World"

问题在于encodeBase64会在每76个字符后添加一个换行符,这会破坏字符串的长度。我最终使用了def encoded = byteArray.collect { it as char }而不是Base64编码。 - Josh K
12
默认情况下,自Groovy 1.6.0版本开始,编码中不会插入额外的换行符。调用encodeBase64(true)可以启用该行为。 - ataylor


2
你可以使用开源的Base64Coder库。
import biz.source_code.base64Coder.Base64Coder

@Grab(group='biz.source_code', module='base64coder', version='2010-09-21')

String s1 = Base64Coder.encodeString("Hello world")
String s2 = Base64Coder.decodeString("SGVsbG8gd29ybGQ=")

2

实现你自己的方法就像这样 :)

public class Coder {
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

public static String encodeAsBase64(String toEncode) {
    return encodeAsBase64(toEncode.getBytes())
}

public static String encodeAsBase64(byte[] toEncode) {
    int pos = 0;
    int onhand = 0;

    StringBuffer buffer = new StringBuffer();
    for(byte b in toEncode) {
        int read = b;
        int m;
        if(pos == 0) {
            m = (read >> 2) & 63;
            onhand = read & 3;
            pos = 1;
        } else if(pos == 1) {
            m = (onhand << 4) + ((read >> 4) & 15);
            onhand = read & 15;
            pos = 2;
        } else if(pos == 2) {
            m = ((read >> 6) & 3) + (onhand << 2);
            onhand = read & 63;
            buffer.append(base64code.charAt(m));
            m = onhand;
            onhand = 0;
            pos  = 0;
        }
        buffer.append(base64code.charAt(m));
    }
    while(pos > 0 && pos < 4) {
        pos++;
        if(onhand == -1) {
            buffer.append('=');
        } else {
            int m = pos == 2 ? onhand << 4 : (pos == 3 ? onhand << 2 : onhand);
            onhand = -1;
            buffer.append(base64code.charAt(m));
        }
    }
    return buffer.toString()
}

}


0
(将此添加到本主题中,希望其他人能够找到这个线索,不必浪费宝贵的时间)
今天我遇到了困难,当我尝试在我的Grails 2.3.11 / Groovy 2.1.9应用程序中添加输出时。
String src = render(
        model:    ...,
        template: ...,
    )
    .encodeAsBase64()

将Base64字符串作为DOM元素的data-属性。但是相应的JavaScript中的atob(),即从数据属性解码Base64字符串的代码,一直抱怨存在非法字符,而其他解码器(例如base64 -d)则可以毫无问题地接受相同的Base64字符串。

解决方案是强制render()返回值为单个字符串,然后应用Base64编码,即:

String src = render(
        model:    ...,
        template: ...,
    )
    .toString()
    .encodeAsBase64()

或者(如果您认为encodeAsBase64()已过时):

String src = render(
        model:    ...,
        template: ...,
    )
    .toString()
    .bytes
    .encodeBase64() // add 'true' for chunked output

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接