Saturday, 10 February 2018

Convert certificate into base64 encoded string

In my previous post, I explained how to create and export a self-signed certificate using ‘keytool’ command. In this post, I am going to show you how to convert the certificate into base64 encoded string.

To run this program, you need to create a self-signed certificate and pass the path of the file as an input to the application Test.java.

CertificateUtil.java
package com.sample.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 CertificateUtil {
 private static final int BUFFER_SIZE = 65535;

 /**
  * 
  * 
  * @param certificateFilePath
  * @return the base64 encoded array from given certificate content.
  * 
  * @throws Exception
  */
 public static byte[] convertCertificateToByteArray(String certificateFilePath) throws Exception {
  if (certificateFilePath == null || certificateFilePath.isEmpty()) {
   throw new Exception("certificateFilePath should not be null or empty");
  }

  File file = new File(certificateFilePath);

  if (!file.exists()) {
   throw new Exception("File not exist : " + file.getAbsolutePath());
  }

  if (file.isDirectory()) {
   throw new Exception("File shouldn't be a directory : " + file.getAbsolutePath());
  }

  try (InputStream inputStream = new FileInputStream(file)) {

   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   byte[] buffer = new byte[BUFFER_SIZE];
   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);
   return encodedBytes;

  }
 }

 /**
  * Convert the certificate into base64 encoded string.
  * 
  * @param certificateFilePath
  * @return
  * @throws Exception
  */
 public static String convertCertificateToString(String certificateFilePath) throws Exception {

  byte[] encodedBytes = convertCertificateToByteArray(certificateFilePath);
  String str = new String(encodedBytes);

  return str;

 }
}

Test.java
package com.sample.test;

import com.sample.util.CertificateUtil;

public class Test {
 public static void main(String args[]) throws Exception {
  String certificateFilePath = "C:\\Users\\krishna\\myCert.cer";
  
  String certificateInfo = CertificateUtil.conv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