Encoding as Base64 in Java

前端 未结 17 2502
失恋的感觉
失恋的感觉 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:53

    You can also convert using Base64 encoding. To do this, you can use the javax.xml.bind.DatatypeConverter#printBase64Binary method.

    For example:

    byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
    System.out.println(DatatypeConverter.printBase64Binary(salt));
    
    0 讨论(0)
  • 2020-11-21 13:53
    public String convertImageToBase64(String filePath) {
        byte[] fileContent = new byte[0];
        String base64encoded = null;
        try {
            fileContent = FileUtils.readFileToByteArray(new File(filePath));
        } catch (IOException e) {
            log.error("Error reading file: {}", filePath);
        }
        try {
            base64encoded = Base64.getEncoder().encodeToString(fileContent);
        } catch (Exception e) {
            log.error("Error encoding the image to base64", e);
        }
        return base64encoded;
    }
    
    0 讨论(0)
  • 2020-11-21 13:57

    I tried with the following code snippet. It worked well. :-)

    com.sun.org.apache.xml.internal.security.utils.Base64.encode("The string to encode goes here");
    
    0 讨论(0)
  • 2020-11-21 13:58

    In Java 8 it can be done as: Base64.getEncoder().encodeToString(string.getBytes(StandardCharsets.UTF_8))

    Here is a short, self-contained complete example:

    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public class Temp {
        public static void main(String... args) throws Exception {
            final String s = "old crow medicine show";
            final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);
            final String encoded = Base64.getEncoder().encodeToString(authBytes);
            System.out.println(s + " => " + encoded);
        }
    }
    

    Output:

    old crow medicine show => b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==
    
    0 讨论(0)
  • 2020-11-21 14:00

    Here are my two cents... Java 8 does contain its own implementation of Base64. However, I found one slightly disturbing difference. To illustrate, I will provide a code example:

    My codec wrapper:

    public interface MyCodec
    {
      static String apacheDecode(String encodedStr)
      {
        return new String(Base64.decodeBase64(encodedStr), Charset.forName("UTF-8"));
      }
    
      static String apacheEncode(String decodedStr)
      {
        byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
        return Base64.encodeBase64String(decodedByteArr);
      }
    
      static String javaDecode(String encodedStr)
      {
        return new String(java.util.Base64.getDecoder().decode(encodedStr), Charset.forName("UTF-8"));
      }
    
      static String javaEncode(String decodedStr)
      {
        byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
        return java.util.Base64.getEncoder().encodeToString(decodedByteArr);
      }
    }
    

    Test Class:

    public class CodecDemo
    {
      public static void main(String[] args)
      {
        String decodedText = "Hello World!";
    
        String encodedApacheText = MyCodec.apacheEncode(decodedText);
        String encodedJavaText = MyCodec.javaEncode(decodedText);
    
        System.out.println("Apache encoded text: " + MyCodec.apacheEncode(encodedApacheText));
        System.out.println("Java encoded text: " + MyCodec.javaEncode(encodedJavaText));
    
        System.out.println("Encoded results equal: " + encodedApacheText.equals(encodedJavaText));
    
        System.out.println("Apache decode Java: " + MyCodec.apacheDecode(encodedJavaText));
        System.out.println("Java decode Java: " + MyCodec.javaDecode(encodedJavaText));
    
        System.out.println("Apache decode Apache: " + MyCodec.apacheDecode(encodedApacheText));
        System.out.println("Java decode Apache: " + MyCodec.javaDecode(encodedApacheText));
      }
    }
    

    OUTPUT:

    Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA0K
    
    Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Encoded results equal: false
    Apache decode Java: Hello World!
    Java decode Java: Hello World!
    Apache decode Apache: Hello World!
    Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character d
        at java.util.Base64$Decoder.decode0(Base64.java:714)
        at java.util.Base64$Decoder.decode(Base64.java:526)
        at java.util.Base64$Decoder.decode(Base64.java:549)
    

    Notice that the Apache encoded text contain additional line breaks (white spaces) at the end. Therefore, in order for my codec to yield the same result regardless of Base64 implementation, I had to call trim() on the Apache encoded text. In my case, I simply added the aforementioned method call to the my codec's apacheDecode() as follows:

    return Base64.encodeBase64String(decodedByteArr).trim();
    

    Once this change was made, the results are what I expected to begin with:

    Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
    Encoded results equal: true
    Apache decode Java: Hello World!
    Java decode Java: Hello World!
    Apache decode Apache: Hello World!
    Java decode Apache: Hello World!
    

    CONCLUSION: If you want to switch from Apache Base64 to Java, you must:

    1. Decode encoded text with your Apache decoder.
    2. Encode resulting (plain) text with Java.

    If you switch without following these steps, most likely you will run into problems. That is how I made this discovery.

    0 讨论(0)
  • 2020-11-21 14:00

    In Java 7 I coded this method

    import javax.xml.bind.DatatypeConverter;
    
    public static String toBase64(String data) {
        return DatatypeConverter.printBase64Binary(data.getBytes());
    }
    
    0 讨论(0)
提交回复
热议问题