首页 > 解决方案 > Java中的Base64编码,使用android.util.Base64

问题描述

我知道,关于这个主题有很多线索——我已经阅读了大部分内容,但没有一个给我正确的答案。

我有以下代码:

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Crypter {

    public static void main(String[] args) {
        String data = "Arnab C";
        final String enc = DarKnight.getEncrypted(data);
        System.out.println("Encrypted : " + enc);
        System.out.println("Decrypted : " + DarKnight.getDecrypted(enc));
    }

    static class DarKnight {

        private static final String ALGORITHM = "AES";

        private static final byte[] SALT = "tHeApAcHe6410111".getBytes();// THE KEY MUST BE SAME
        private static final String X = DarKnight.class.getSimpleName();

        static String getEncrypted(String plainText) {

            if (plainText == null) {
                return null;
            }

            Key salt = getSalt();

            try {
                Cipher cipher = Cipher.getInstance(ALGORITHM);
                cipher.init(Cipher.ENCRYPT_MODE, salt);
                byte[] encodedValue = cipher.doFinal(plainText.getBytes());
                return Base64.encode(encodedValue,Base64.DEFAULT);


            } catch (Exception e) {
                e.printStackTrace();
            }

            throw new IllegalArgumentException("Failed to encrypt data");
        }

        public static String getDecrypted(String encodedText) {

            if (encodedText == null) {
                return null;
            }

            Key salt = getSalt();
            try {
                Cipher cipher = Cipher.getInstance(ALGORITHM);
                cipher.init(Cipher.DECRYPT_MODE, salt);
                byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);
                byte[] decValue = cipher.doFinal(decodedValue);
                return new String(decValue);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        static Key getSalt() {
            return new SecretKeySpec(SALT, ALGORITHM);
        }

    }

}

我从PHP 和 Java 之间的加密中复制了这个- 但改变了

import com.sun.org.apache.xml.internal.security.utils.Base64;

import android.util.Base64;

因为 apache-version 在 Java8 中不起作用。

由于这种变化,我不得不向 Base64.decode 和 Base64.encode 添加一个标志。在解码中工作正常:

byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);

但是当向 Base64.encode 添加一个标志时,会发生一些奇怪的事情:

当我写“return Base64.encode(”时,Android Studio 告诉我它需要一个 byte[] 输入和一个 int 标志。所以我想,我可以简单地使用变量 encodedValue 作为第一个参数,因为那是一个 byte[] . 作为下一个参数,我可以使用 Base64.DEFAULT,它是一个值为 0 的 int。但 Android Studio 不同意:不兼容的类型,必需:java.lang.String,找到:byte[]。

为什么 Android Studio 需要一个字符串,当它第一次说它需要一个 byte[] 时?

实际上,“为什么”并不重要,更重要的是:我该如何解决这个问题?

任何帮助,将不胜感激。

标签: javaandroidencryptionbase64

解决方案


使用encodeToString()而不是encode(). 第一个String按您的函数返回类型返回 a ,后者返回 a byte[]

文档:https ://developer.android.com/reference/android/util/Base64


推荐阅读