Base64 java для android

Кодирование и декодирование Java Base64

Как сделать кодирование и декодирование Base64 в Java, используя новые API, представленные в Java 8, а также Apache Commons.

Автор: baeldung
Дата записи

1. Обзор

В этом уроке мы рассмотрим различные утилиты, которые предоставляют функции кодирования и декодирования Base64 в Java.

Мы в основном собираемся проиллюстрировать новые API Java 8 и служебные API, которые выходят из Apache Commons.

Дальнейшее чтение:

Руководство по кодированию/декодированию URL-адресов Java

Хеширование SHA-256 и SHA3-256 в Java

Новое Хранилище Паролей В Spring Security 5

2. Java 8 для базы 64

Java 8 наконец-то добавила возможности Base64 в стандартный API. Это делается через класс утилиты java.util.Base64 .

Давайте начнем с рассмотрения базового процесса кодирования.

2.1. Java 8 Basic Base64

Базовый кодер упрощает работу и кодирует вход как есть, без какого-либо разделения строк.

Выходные данные отображаются на набор символов в A-Za-z0-9+/ набор символов, и декодер отклоняет любой символ за пределами этого набора.

Давайте сначала закодируем простую строку :

Обратите внимание, как мы получаем полный API кодировщика с помощью простого метода GetEncoder() utility.

Теперь давайте расшифруем эту строку обратно в исходную форму:

2.2. Кодировка Java 8 Base64 Без Заполнения

В кодировке Base64 длина выходной кодированной строки должна быть кратна трем. Если нет, то вывод будет дополнен дополнительными символами pad ( = ).

После декодирования эти дополнительные символы заполнения будут отброшены. Чтобы углубиться в заполнение в Base64, ознакомьтесь с этим подробным ответом на Переполнение стека .

Если нам нужно пропустить заполнение вывода — возможно, потому, что результирующая строка никогда не будет декодирована обратно — мы можем просто выбрать кодирование без заполнения :

2.3. Кодировка URL-адресов Java 8

Кодировка URL-адресов очень похожа на базовый кодер, который мы рассмотрели выше. Он использует безопасный алфавит Base64 URL и имени файла и не добавляет никакого разделения строк:

Читайте также:  Что делать когда тормозит андроид

Декодирование происходит во многом таким же образом. Метод утилиты getUrlDecoder() возвращает java.util.Base64.Decoder , который затем используется для декодирования URL-адреса:

2.4. Кодировка MIME Java 8

Давайте начнем с создания некоторого базового ввода MIME для кодирования:

Кодер MIME генерирует выходные данные в кодировке Base64, используя базовый алфавит, но в удобном для MIME формате.

Каждая строка вывода содержит не более 76 символов и заканчивается возвратом каретки, за которым следует перевод строки ( \r\n ):

Метод утилиты getMimeDecoder() возвращает java.util.Base64.Decoder , который затем используется в процессе декодирования:

3. Кодирование/Декодирование С Использованием Кодека Apache Commons

Во-первых, нам нужно определить зависимость commons-codec в pom.xml :

Обратите внимание, что мы можем проверить, были ли выпущены более новые версии библиотеки на Maven Central .

Основным API является класс org.apache.commons.codec.binary.Base64 , который может быть параметризован с помощью различных конструкторов:

  • Base64(boolean urlSafe) создает API Base64, управляя включенным или выключенным режимом URL-safe.
  • Base64 (int lineLength) создает API Base64 в небезопасном для URL режиме и управляет длиной строки (по умолчанию 76).
  • Base64(int lineLength, byte[] LineSeparator) создает API Base64, принимая дополнительный разделитель строк, который по умолчанию является CRLF (“\r\n”).

После создания API Base64 и кодирование, и декодирование довольно просты:

Метод decode() класса Base64 возвращает декодированную строку:

Другим простым вариантом является использование статического API Base64 |/вместо создания экземпляра:

4. Преобразование строки в массив байтов

Иногда нам нужно преобразовать Строку в байт[] . Самый простой способ сделать это-использовать метод String getBytes() :

Лучше также обеспечить кодировку и не зависеть от кодировки по умолчанию, так как она зависит от системы:

Если наша строка Base64 закодирована, мы можем использовать декодер Base64 |:

Мы также можем использовать DatatypeConverter parseBase64Binary() метод :

Наконец, мы можем преобразовать шестнадцатеричную строку в байт[] с помощью метода DatatypeConverter :

5. Заключение

В этой статье объясняются основы кодирования и декодирования Base64 в Java с использованием новых API, представленных в Java 8 и Apache Commons.

Источник

How to Encode and Decode Image in Base64 in Android?

Here, we are going to make an application of the “Encoding-Decoding” of an image. By making this application we will be able to learn that how we can encode an image in Base64. We will also be decoding our image with help of a button.

Читайте также:  Что такое passbook для android

Prerequisite:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

Before proceeding with this application you should be aware of Base64 in java. If you are not aware of it, use Basic Type Base64 Encoding and Decoding in Java.

What we are going to build in this article?

In this application, we will be using two buttons Encode and Decode to perform their respective operations. Moreover, we will be using a textView to display encoded text and finally an imageView to display the decoded image. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Creating a new project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?

Step 2: Navigate to app > Manifests > AndroidManifest.xml file and add the following permission to it

Step 3: Working with the activity_main.xml file

Here we will design the user interface of our application. We will be using the following components for their respective works:

  • TextView – to show the encoded text
  • ImageView – to show the decoded image.
  • Button – to encode or decode the image on click.

Источник

Base64

Something Sun Should Have Included Long Ago

(And now has! As of Java v1.8, there is a Base64 class. Finally.)

This is a Public Domain Java class providing very fast Base64 encoding and decoding in the form of convenience methods and input/output streams.

Читайте также:  System backup and restore android что это

There are other Base64 utilities on the Internet, some part of proprietary packages, some with various open source licenses. In any event, I hope with one or more of these Base64 tools, you won’t have to write your own like I did.

If you use Maven, thank Owen O’Malley from Apache and Matthew from Sensible Development for working up a Base64 Maven Repository.

Thanks to Brian Burton for providing this Base64Test.java test class for use with JUnit.org. (The test file hasn’t been updated in a while.)

You may view the Base64 javadoc API online, if you like.

Version 2.3 is not a drop-in replacement to earlier versions. I finally improved the error handling such that the code will throw exceptions when there is a problem instead of just quietly returning null. Sorry if you like the old style (I did too for a long time), but I changed it and think it’s better form this way. There are also some helper methods for encoding data without creating a String object; that should help with very large amounts of data or when memory is tight.

Examples

The easiest way to convert some data is with the convenience methods:

Or you can use the very efficient streams:

There are defaults (OutputStream encodes, InputStream decodes), but you can easily override that:

A Note About Public Domain

I have released this software into the Public Domain. That means you can do whatever you want with it. Really. You don’t have to match it up with any other open source license &em; just use it. You can rename the files, move the Java packages, whatever you want. If your lawyers say you have to have a license, contact me, and I’ll make a special release to you under whatever reasonable license you desire: MIT, BSD, GPL, whatever.

Alternatives

There are alternative Base64 classes out there. For various reasons you might prefer them. It’s OK; you won’t hurt my feelings. Keep in mind particularly that there are a lot of «helper functions» in the Base64.java class available on this page, and if you’re doing embedded work, you’ll either want to strip out the fluff or just grab a more minimal implementation. Here are some that I’ve found:

Источник

Оцените статью