使用 Java Android 将 base64 编码字符串转换为 p12 文件的正确方法

问题描述

我有一个由 API 返回的 base64 编码字符串 p12 文件。我正在尝试将其保存到文件中,但在我的手机上打开它时不起作用。

出了什么问题: 解码字符串并将其保存到 .p12 文件后。该文件无法打开,因为它似乎已损坏。我试图找到另一种方法来解码 base64 字符串以使其工作。

我尝试过的:

  1. 调用 API 获取 Base64 编码的字符串
  2. 使用我在搜索时得到的以下代码对其进行解码(感谢所有者)。
   public static byte[] decode(String data)
     {
       int[] tbl = {
               -1,-1,62,63,52,53,54,55,56,57,58,59,60,61,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1 };
       byte[] bytes = data.getBytes();
       ByteArrayOutputStream buffer = new ByteArrayOutputStream();
       for (int i = 0; i < bytes.length; ) {
           int b = 0;
           if (tbl[bytes[i]] != -1) {
               b = (tbl[bytes[i]] & 0xFF) << 18;
           }
           // skip unkNown characters
           else {
               i++;
               continue;
           }

           int num = 0;
           if (i + 1 < bytes.length && tbl[bytes[i+1]] != -1) {
               b = b | ((tbl[bytes[i+1]] & 0xFF) << 12);
               num++;
           }
           if (i + 2 < bytes.length && tbl[bytes[i+2]] != -1) {
               b = b | ((tbl[bytes[i+2]] & 0xFF) << 6);
               num++;
           }
           if (i + 3 < bytes.length && tbl[bytes[i+3]] != -1) {
               b = b | (tbl[bytes[i+3]] & 0xFF);
               num++;
           }

           while (num > 0) {
               int c = (b & 0xFF0000) >> 16;
               buffer.write((char)c);
               b <<= 8;
               num--;
           }
           i += 4;
       }
       return buffer.toByteArray();
   }
  1. 使用此代码将其保存到文件中。
public void writeBytesToFile(String encodedString)
            throws IOException {


        byte[] decodedBytes =  decode(encodedString);


        File directory = new File("storage/emulated/0/","Certificates");
        if(!directory.exists()){
            directory.mkdir();
        }
        Log.d("BYTS",new String(decodedBytes));



        String fileFilname = certTypestr.concat("p12file.pem");
        //Toast.makeText(MyApplication.getAppContext(),fileFilname,Toast.LENGTH_SHORT).show();
        File file = new File("storage/emulated/0/Certificates",fileFilname);

        if(!file.exists()){
            boolean createfile = file.createNewFile();
        }else{
            boolean deletefile = file.delete();
            boolean createfile = file.createNewFile();
        }


        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(decodedBytes);
        }




    }

但似乎我没有运气让它工作。请帮助我正确地将 base64 字符串转换为 p12 文件

解决方法

对于那些试图做同样事情的人来说,经过数小时的反复试验。我通过运行 Shell 命令来使用 Java ProcessBuilder 解码 base64 字符串来使其工作。使用的命令:

base64 -d test.txt | base64 -d > test.p12

我不知道为什么 base64 解码的输出与 windows 和 linux 命令行不同,但这种解决方法很有用。