Base64 Java 编码和解码字符串 [英] Base64 Java encode and decode a string

查看:61
本文介绍了Base64 Java 编码和解码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串编码为 base64 并通过套接字传输它并解码回来.

I want to encode a string into base64 and transfer it through a socket and decode it back.

但解码后给出了不同的答案.

But after decoding it gives different answer.

以下是我的代码,结果是77+9x6s="

Following is my code and result is "77+9x6s="

import javax.xml.bind.DatatypeConverter;

    public class f{

       public static void main(String a[]){

          String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
          String res = DatatypeConverter.printBase64Binary(str.getBytes());
          System.out.println(res);
       }
    }

知道如何实现这一点吗?

Any idea about how to implement this?

推荐答案

您可以使用以下方法:

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));

// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));

希望这能解答您的疑问.

Hope this answers your doubt.

这篇关于Base64 Java 编码和解码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆