Read/Write Certificate Signing Request on Android (spongycastle)

Tags: , , , ,



I try to write code on Android to generate RSA key-pair and then generate Certificate Request file (.csr) like this image below:

enter image description here

  1. First I use spongycastle lib to generate Key Pair (public key and private key)

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024,new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    publicKey = keyPair.getPublic();
    privateKey = keyPair.getPrivate();
    
  2. Then I use CSRHelper class I found on this link to generate: byte CSRder[]:

    byte CSRder[] = csr.getEncoded();
    
  3. I write code to write byte[] to file:

    File file;
    FileOutputStream outputStream;
    try
    {
        file = new File(getCacheDir(),"csr.txt");
        outputStream = new FileOutputStream(file);
        outputStream.write(CSRder);
        outputStream.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    
  4. Final I write code to read file again:

    BufferedReader input = null;
    File file = null;
    try {
       file = new File(getCacheDir(), "csr.txt"); // Pass getFilesDir() and "MyFile" to read file
    
        input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = input.readLine()) != null) {
              buffer.append(line);
        }
        Log.d(TAG, buffer+"");
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    

But my logcat show unreadable character.

    07-21 13:48:35.163 16157-16157/com.example.napoleon.test_2 D/MainActivity: 0��0���0;10Unapoleon.com10UAralink10UOrgUnit0��0 *�H��������0�������Qt��G�]�ܪ�0�'�I^�Q��[�r5ڢ_!|������ZC��~<��*o�?�d+-����)��V�<߹��m��(��ѐxDcx��NhƬF��Ҵvq+���0�Iq�-Eoe,���"0     *�H��   100U�0�0    *�H���������YPT3��?��P5MY��hs)��$1Gv�r_��76ߞ;���ҽ�޼ t�kI�I��Z��tg����O�W��Gt�=���V���#G1�$z�$�V����_^7_x�?�0�׵#�;��f?�

How to write this csr byte to file and read again?

Answer

CSRder is binary, you can not read it as string because it has non-printable characters.

Since you require PEM format for .csr file, it is needed to convert the binary content to base64 and add the PEM header and footer

----BEGIN CERTIFICATE REQUEST-----
(base64)
----END CERTIFICATE REQUEST-----

This can be done manually or using spongycastle’s PEMWriter

StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", CSRder));
pemWriter.flush();
pemWriter.close();
String csrPEM = writer.toString();

After this, you can save csrPEM as string file.



Source: stackoverflow