Encoding as Base64 in Java

前端 未结 17 2471
失恋的感觉
失恋的感觉 2020-11-21 13:44

I need to encode some data in the Base64 encoding in Java. How do I do that? What is the name of the class that provides a Base64 encoder?


I tried to use the <

相关标签:
17条回答
  • 2020-11-21 13:47

    If you are using Spring Framework at least version 4.1, you can use the org.springframework.util.Base64Utils class:

    byte[] raw = { 1, 2, 3 };
    String encoded = Base64Utils.encodeToString(raw);
    byte[] decoded = Base64Utils.decodeFromString(encoded);
    

    It will delegate to Java 8's Base64, Apache Commons Codec, or JAXB DatatypeConverter, depending on what is available.

    0 讨论(0)
  • 2020-11-21 13:48

    On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Android 2.2 (Froyo)).

    import android.util.Base64;
    
    byte[] encodedBytes = Base64.encode("Test".getBytes());
    Log.d("tag", "encodedBytes " + new String(encodedBytes));
    
    byte[] decodedBytes = Base64.decode(encodedBytes);
    Log.d("tag", "decodedBytes " + new String(decodedBytes));
    
    0 讨论(0)
  • 2020-11-21 13:49

    Use Java 8's never-too-late-to-join-in-the-fun class: java.util.Base64

    new String(Base64.getEncoder().encode(bytes));
    
    0 讨论(0)
  • 2020-11-21 13:50

    For Java 6-7, the best option is to borrow code from the Android repository. It has no dependencies.

    https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Base64.java

    0 讨论(0)
  • 2020-11-21 13:50

    Simple example with Java 8:

    import java.util.Base64;
    
    String str = "your string";
    String encodedStr = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
    
    0 讨论(0)
  • 2020-11-21 13:51

    Apache Commons has a nice implementation of Base64. You can do this as simply as:

    // Encrypt data on your side using BASE64
    byte[] bytesEncoded = Base64.encodeBase64(str .getBytes());
    System.out.println("ecncoded value is " + new String(bytesEncoded));
    
    // Decrypt data on other side, by processing encoded data
    byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
    System.out.println("Decoded value is " + new String(valueDecoded));
    

    You can find more details about base64 encoding at Base64 encoding using Java and JavaScript.

    0 讨论(0)
提交回复
热议问题