This article is about how to convert the certificate file into one line base 64 encoded string.
This can be done in many ways. This article is going to talk about,
- Java programming approach
- Unix command line approach
For this exercise, I have downloaded certificate from stackoverflow.com and going to convert the cer file into one line base 64 encoded string
# Command Line Approach
- uuencode is the command (unix)
- Execute the below command to encode certificate file into text format. this would create the stackoverflow_encode.txt in the same directory
uuencode -m stackoverflow.cer stackoverflow_temp_decode.txt > stackoverflow_encode.txt

- Open the stackoverflow_encode.txt and remove the first line and the last line and save the file.
- Now execute the below command to format the encoded string into one line. This would create stackoverflow_encode_formatted.txt
awk ‘NF {sub(/\r/, “”); printf “%s”,$0;}’ stackoverflow_encode.txt > stackoverflow_encode_formatted.txt

# Java Approach
- Java program to convert the certificate file into one line encrypted string.
package com.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Base64.Encoder;
public class ConvertCertificateToBase64EncodedString {
public static void main(String[] args) throws Exception {
String certPath = "C:\\cert\\stackoverflow.cer";
File file = new File(certPath);
try (InputStream inputStream = new FileInputStream(file)) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[65535];
int numberOfReadBytes;
while ((numberOfReadBytes = inputStream.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, numberOfReadBytes);
}
byte[] certificateInBytes = byteArrayOutputStream.toByteArray();
Encoder encoder = Base64.getEncoder();
byte[] encodedBytes = encoder.encode(certificateInBytes);
String base64EncodedString = new String(encodedBytes);
System.out.println(base64EncodedString);
}
}
}
- Console output
