Java / Groovy 中的 Base64 编码

发布于 2024-10-02 18:39:03 字数 176 浏览 2 评论 0原文

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

What is the proper way to convert a byte [] to a Base64 string in Java? Better yet would be Grails / Groovy because it tells me that the encodeAsBase64() function is deprecated. The sun.misc.BASE64Encoder package isn't recommended for use and outputs a different size string on some Windows platforms.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

束缚m 2024-10-09 18:39:03

在 groovy 中执行此操作的首选方法是:

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

The preferred way to do this in groovy is:

 def encoded = "Hello World".bytes.encodeBase64().toString()
 assert encoded == "SGVsbG8gV29ybGQ="
 def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
 assert decoded == "Hello World"
爱殇璃 2024-10-09 18:39:03

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

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()
}

}

Implement your own method like this :)

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()
}

}

迷爱 2024-10-09 18:39:03

您可以使用开源 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=")

You could use the open source Base64Coder library

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=")
紫轩蝶泪 2024-10-09 18:39:03

(将其添加到此线程中是希望其他人能够对此感兴趣,而不必浪费他的宝贵时间)

今天,当我尝试添加 Grails 2.3.11/Groovy 2.1.9 应用程序时,我遇到了阻碍 的输出

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

作为 DOM 元素的 data- 属性 。但是相应JavaScript中的atob(),即从data属性解码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

(adding this to this thread in the hopes that somebody else will get a hit on this and doesn't have to waste his valuable time)

I got stymied today when I tried to add in my Grails 2.3.11/Groovy 2.1.9 application the output of

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

as a data- attribute to a DOM element. But the atob() in the corresponding JavaScript, i.e. the code that decodes the Base64 string from the data attribute, kept complaining about illegal characters, while other decoders, e.g. base64 -d accepted the same Base64 string without problems.

The solution is to force the render() return value to a single string and then apply the Base64 encoding, i.e.

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

or (if you consider encodeAsBase64() as deprecated):

String src = render(
        model:    ...,
        template: ...,
    )
    .toString()
    .bytes
    .encodeBase64() // add 'true' for chunked output
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文