【问题标题】:Base 64 encode and decode example codeBase 64 编码和解码示例代码
【发布时间】:2022-01-10 20:56:14
【问题描述】:

有谁知道如何使用 Base64 解码和编码 Base64 中的字符串。我正在使用以下代码,但它不起作用。

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)));

【问题讨论】:

  • 你必须导入这个import android.util.Base64;,然后可以根据你的需要使用Base64.encodeToString & Base64.decode

标签: java android base64


【解决方案1】:

2021 年 kotlin 的答案

编码:

        val data: String = "Hello"
        val dataByteArray: ByteArray = data.toByteArray()
        val dataInBase64: String = Base64Utils.encode(dataByteArray)

解码:

        val dataInBase64: String = "..."
        val dataByteArray: ByteArray = Base64Utils.decode(dataInBase64)
        val data: String = dataByteArray.toString()

【讨论】:

  • 谢谢!如果您的 API 最小值设置为 ,则仅访问 Base64.getEncoder 不可用
【解决方案2】:

上面有很多答案,但对我不起作用,其中一些没有以正确的方式处理异常。这里我添加了一个完美的解决方案,对我来说也很棒。

//base64 decode string 
 String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
    ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
    String val = a(s) ;
     Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
    
       public static String a(String str) {
             try {
                 return new String(Base64.decode(str, 0), "UTF-8");
             } catch (UnsupportedEncodingException | IllegalArgumentException unused) {
                 return "This is not a base64 data";
             }
         }

【讨论】:

    【解决方案3】:

    'java.util.Base64' 类提供以 Base64 格式编码和解码信息的功能。

    如何获取 Base64 编码器?

    Encoder encoder = Base64.getEncoder();
    

    Base64解码器如何获取?

    Decoder decoder = Base64.getDecoder();
    

    如何对数据进行编码?

    Encoder encoder = Base64.getEncoder();
    String originalData = "java";
    byte[] encodedBytes = encoder.encode(originalData.getBytes());
    

    如何解码数据?

    Decoder decoder = Base64.getDecoder();
    byte[] decodedBytes = decoder.decode(encodedBytes);
    String decodedStr = new String(decodedBytes);
    

    您可以在此link 获取更多详细信息。

    【讨论】:

    • 这可能会在某些设备上导致 ClassNotFoundException。 Imo 你应该使用 android.util.Base64 代替(假设我们在一个 android 上下文中,基于标签)。
    【解决方案4】:

    用于android API byte[]Base64String 编码器

    byte[] data=new byte[];
    String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
    

    【讨论】:

    • 注意,这已经过时了,我认为从 Android API 26 开始。改用Base64.getEncoder().encodeToString(data)
    【解决方案5】:
    package net.itempire.virtualapp;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Base64;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class BaseActivity extends AppCompatActivity {
    EditText editText;
    TextView textView;
    TextView textView2;
    TextView textView3;
    TextView textView4;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_base);
            editText=(EditText)findViewById(R.id.edt);
            textView=(TextView) findViewById(R.id.tv1);
            textView2=(TextView) findViewById(R.id.tv2);
            textView3=(TextView) findViewById(R.id.tv3);
            textView4=(TextView) findViewById(R.id.tv4);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                 textView2.setText(Base64.encodeToString(editText.getText().toString().getBytes(),Base64.DEFAULT));
                }
            });
    
            textView3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textView4.setText(new String(Base64.decode(textView2.getText().toString(),Base64.DEFAULT)));
    
                }
            });
    
    
        }
    }
    

    【讨论】:

      【解决方案6】:
          <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:orientation="vertical"
          android:layout_height="match_parent"
          tools:context=".BaseActivity">
         <EditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:id="@+id/edt"
             android:paddingTop="30dp"
             />
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/tv1"
              android:text="Encode"
              android:textSize="20dp"
              android:padding="20dp"
              />
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/tv2"
      
              android:textSize="20dp"
              android:padding="20dp"
              />
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/tv3"
              android:text="decode"
              android:textSize="20dp"
              android:padding="20dp"
              />
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/tv4"
              android:textSize="20dp"
              android:padding="20dp"
      
      
              />
      </LinearLayout>
      

      【讨论】:

      • 这是在android studio中通过base64编码和dcode
      • 请在回答中更新您的评论。还要在单一答案中发布 Java 和 XML。
      • 写一些解释和一些代码总是一个好习惯。谢谢!
      【解决方案7】:

      对于 API 级别 26+

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

      参考: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte[])

      【讨论】:

        【解决方案8】:

        Kotlin mb 最好使用这个:

        fun String.decode(): String {
            return Base64.decode(this, Base64.DEFAULT).toString(charset("UTF-8"))
        }
        
        fun String.encode(): String {
            return Base64.encodeToString(this.toByteArray(charset("UTF-8")), Base64.DEFAULT)
        }
        

        例子:

        Log.d("LOGIN", "TEST")
        Log.d("LOGIN", "TEST".encode())
        Log.d("LOGIN", "TEST".encode().decode())
        

        【讨论】:

        • 这些扩展功能的命名是可怕的。我强烈建议使用 encodeToBase64 或类似的东西。
        • 它们绝对不清晰和明显。告诉我:“解码”或“编码”是什么意思?有成千上万的解码/编码算法......如果你需要 Base64 和 Hex 怎么办?那么你会如何命名这些方法呢?
        • 更不用说不同的 Base64 标准了。
        • 不过我更喜欢类似:'toBase64()' 和 'fromBase64()' 作为最低要求。这样我不需要阅读任何文档就可以知道该方法会做什么。请记住:“阅读的代码多于编写的代码”。
        • 举个例子就这么大惊小怪:)
        【解决方案9】:

        加密:

        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");
        

        【讨论】:

          【解决方案10】:

          如果你使用的是 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"))
          

          【讨论】:

          • 或者您可以使用 Charsets.UTF_8 代替 charset("UTF-8")。
          • @makovkastar 确认一下,现在是 StandardCharsets.UTF_8
          【解决方案11】:

          根据之前的答案,我正在使用以下实用方法,以防有人想使用它。

              /**
           * @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;
          }
          

          【讨论】:

            【解决方案12】:

            第一:

            • 选择一种编码。 UTF-8 通常是一个不错的选择;坚持使用肯定对双方都有效的编码。很少使用 UTF-8 或 UTF-16 以外的东西。

            发送端:

            • 将字符串编码为字节(例如text.getBytes(encodingName)
            • 使用Base64 类将字节编码为base64
            • 传输base64

            接收端:

            • 接收base64
            • 使用 Base64 类将 base64 解码为字节
            • 将字节解码为字符串(例如new String(bytes, encodingName)

            比如:

            // Sending side
            byte[] data = text.getBytes("UTF-8");
            String base64 = Base64.encodeToString(data, Base64.DEFAULT);
            
            // Receiving side
            byte[] data = Base64.decode(base64, Base64.DEFAULT);
            String text = new String(data, "UTF-8");
            

            或者StandardCharsets:

            // Sending side
            byte[] data = text.getBytes(StandardCharsets.UTF_8);
            String base64 = Base64.encodeToString(data, Base64.DEFAULT);
            
            // Receiving side
            byte[] data = Base64.decode(base64, Base64.DEFAULT);
            String text = new String(data, StandardCharsets.UTF_8);
            

            【讨论】:

            • @max:“它不工作”从来都不能很好地描述正在发生的事情。不过会编辑我的帖子。
            • 另请注意,您不应将静态方法当作实例方法来调用...
            • 如果你这样说它会起作用 String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
            • @portfoliobuilder:绝对不是。 UTF-8 保证是 Java 中的有效编码:请参阅 docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html。诚然,这些天我会指定StandardCharsets.UTF_8。我更新了答案以指定您应该对字符集的存在充满信心,但我几乎总是使用 UTF-8。
            • 当我使用 Base64.DEFAULT 时,它会说 base64 错误。所以使用 Base64.URL_SAFE 和享受者
            【解决方案13】:

            类似

            String source = "password"; 
            byte[] byteArray;
            try {
                byteArray = source.getBytes("UTF-16");
                System.out.println(new String(Base64.decode(Base64.encode(byteArray,
                       Base64.DEFAULT), Base64.DEFAULT)));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            

            【讨论】:

            • 您的回答暗示在 base64 中编码密码是一种很好的做法。事实上它不是任何人都可以简单地解码它。
            【解决方案14】:

            对于在搜索有关如何解码使用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,所以我使用来自 http://iharder.net/base64 的 Robert Harder 的 Base64 库

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-04-03
              • 2017-06-17
              • 2011-10-11
              相关资源
              最近更新 更多