我正在使用下面的代码,但它不起作用。

String source = "password"; 
byte[] byteArray = source.getBytes("UTF-16"); 
Base64 bs = new Base64(); 
//bs.encodeBytes(byteArray); 
System.out.println(bs.encodeBytes(byteArray)); 
//bs.decode(bs.encodeBytes(byteArray));
System.out.println(bs.decode(bs.encodeBytes(byteArray)));

当前回答

加密:

byte[] encrpt= text.getBytes("UTF-8");
String base64 = Base64.encodeToString(encrpt, Base64.DEFAULT);

解密:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");

其他回答

基于之前的答案,我使用以下实用程序方法,以防有人想使用它。

    /**
 * @param message the message to be encoded
 *
 * @return the enooded from of the message
 */
public static String toBase64(String message) {
    byte[] data;
    try {
        data = message.getBytes("UTF-8");
        String base64Sms = Base64.encodeToString(data, Base64.DEFAULT);
        return base64Sms;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * @param message the encoded message
 *
 * @return the decoded message
 */
public static String fromBase64(String message) {
    byte[] data = Base64.decode(message, Base64.DEFAULT);
    try {
        return new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

加密:

byte[] encrpt= text.getBytes("UTF-8");
String base64 = Base64.encodeToString(encrpt, Base64.DEFAULT);

解密:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");

对于在这里结束搜索关于如何解码用Base64.encodeBytes()编码的字符串的信息的任何人,这是我的解决方案:

// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());

// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2); 
String val2 = new String(tmp2, "UTF-8"); 

此外,我支持旧版本的Android,所以我使用Robert Harder的Base64库http://iharder.net/base64

26级火警

String encodedString = Base64.getEncoder().encodeToString(byteArray);

裁判: https://developer.android.com/reference/java/util/Base64.Encoder.html encodeToString (byte [])

如果您正在使用Kotlin,请像这样使用

对编码

val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)

为解码

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))