Home > Enterprise >  Split a certificate string into two separate certificates
Split a certificate string into two separate certificates

Time:11-01

What is the best way to get two certificates from a single certificate string

The string looks like this

-----BEGIN CERTIFICATE-----
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Donec cursus ornare ligula ut porta. Fusce vel orci vitae 
diam faucibus euismod. Donec non elit ut mi iaculis solli
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Suspendisse potenti. Vivamus mauris diam, fermentum sit 
amet mauris ac, maximus consequat mauris. Vivamus elementum 
iaculis lacus nec suscipit
-----END CERTIFICATE-----

What is the best way to split this into two certificates so I get

-----BEGIN CERTIFICATE-----
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Donec cursus ornare ligula ut porta. Fusce vel orci vitae 
diam faucibus euismod. Donec non elit ut mi iaculis solli
-----END CERTIFICATE-----

and

-----BEGIN CERTIFICATE-----
Suspendisse potenti. Vivamus mauris diam, fermentum sit 
amet mauris ac, maximus consequat mauris. Vivamus elementum 
iaculis lacus nec suscipit
-----END CERTIFICATE-----

I have tried splitting by new lines and by the -----BEGIN CERTIFICATE----- and the former obviously doesn't work and the latter leaves behind data

CodePudding user response:

Below code block will solve your problem, i've tested :

val certificates : String = "-----BEGIN CERTIFICATE----- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus ornare ligula ut porta. Fusce vel orci vitae diam faucibus euismod. Donec non elit ut mi iaculis solli -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- Suspendisse potenti. Vivamus mauris diam, fermentum sitamet mauris ac, maximus consequat mauris. Vivamus elementumiaculis lacus nec suscipit -----END CERTIFICATE-----"
        val array: List<String> = certificates.split("-----END CERTIFICATE-----")
        val firstCertificate = array[0]   "-----END CERTIFICATE-----"
        val secondCertificate = array[1]   "-----END CERTIFICATE-----"
        Log.e("firstCertificate", firstCertificate)
        Log.e("secondCertificate", secondCertificate)
  • Related