Wednesday 8 February 2023

Java: Read the keystore file content as base 64 encoded string

In this post, I am going to explain how to read the keystore file content as base 64 encoded string and write the base64 encoded string to a new key store file.

 

To demonstrate the application, let’s create a new keystore file by executing beow command.

keytool -genkey -keyalg RSA -keystore myKeystore.jks -keysize 2048

$keytool -genkey -keyalg RSA -keystore myKeystore.jks -keysize 2048
Enter keystore password:  
Re-enter new password: 
What is your first and last name?
  [Unknown]:  Ram
What is the name of your organizational unit?
  [Unknown]:  hr
What is the name of your organization?
  [Unknown]:  abcCorp
What is the name of your City or Locality?
  [Unknown]:  Bangalore
What is the name of your State or Province?
  [Unknown]:  Karnataka
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=Ram, OU=hr, O=abcCorp, L=Bangalore, ST=Karnataka, C=IN correct?
  [no]:  y

Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 90 days
    for: CN=Ram, OU=hr, O=abcCorp, L=Bangalore, ST=Karnataka, C=IN
$

 

Let’s print the content of keystore file.

$keytool -list -keystore myKeystore.jks 
Enter keystore password:  
Keystore type: PKCS12
Keystore provider: SUN

Your keystore contains 1 entry

mykey, 8 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 7E:2E:8F:1A:6F:94:FA:2A:41:80:0E:39:EA:11:52:2F:A1:64:C0:70:7D:5B:26:3C:39:8A:E6:50:B7:57:60:D6

 

Find the below working application.

 

FileUtil.java

 

package com.sample.app.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class FileUtil {

    public static String readFileContentAsBase64EncodedString(String filePath)
            throws FileNotFoundException, IOException {
        byte[] byteContent = getByteArray(filePath);
        byte[] encoded = Base64.getEncoder().encode(byteContent);
        return new String(encoded);

    }

    public static void writeBase64EncodedStringToFile(final String filePath, final String encodedContent) {
        if (encodedContent == null) {
            throw new IllegalArgumentException("encodedContent is null");
        }
        byte[] decocedBytes = Base64.getDecoder().decode(encodedContent.getBytes());
        writeToFile(filePath, decocedBytes);
    }

    public static boolean writeToFile(final String filePath, final byte[] content) {
        if (filePath == null) {
            throw new IllegalArgumentException("filePath is null");
        }

        if (content == null || content.length == 0) {
            throw new IllegalArgumentException("content is null or empty");
        }

        try (FileOutputStream out = new FileOutputStream(filePath);) {
            out.write(content);
        } catch (Exception e) {
            return false;
        }
        return true;

    }

    public static byte[] getByteArray(final String filePath) throws FileNotFoundException, IOException {

        if (filePath == null) {
            throw new IllegalArgumentException("filePath is null");
        }
        try (final FileInputStream fis = new FileInputStream(new File(filePath))) {
            return getByteArray(fis);
        }
    }

    /**
     * Methods which are calling this method are responsible to close the
     * InputStream.
     * 
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] getByteArray(final InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        try {
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                byteArrayOutputStream.write(data, 0, nRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return byteArrayOutputStream.toByteArray();
    }

}

 

App.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.io.IOException;

import com.sample.app.util.FileUtil;

public class App {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        String filePath = "/Users/Shared/keystore/myKeystore.jks";

        String encodedString = FileUtil.readFileContentAsBase64EncodedString(filePath);
        System.out.println(encodedString);

        String destinationFilePath = "/Users/Shared/keystore/myKeystore1.jks";
        FileUtil.writeBase64EncodedStringToFile(destinationFilePath, encodedString);
    }
}

Run the above application, you will see a file myKeystore1.jks file is created.

 

Let’s print the content of myKeystore1.jks file to confirm the same.

$keytool -list -keystore myKeystore1.jks 
Enter keystore password:  
Keystore type: PKCS12
Keystore provider: SUN

Your keystore contains 1 entry

mykey, 8 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 7E:2E:8F:1A:6F:94:FA:2A:41:80:0E:39:EA:11:52:2F:A1:64:C0:70:7D:5B:26:3C:39:8A:E6:50:B7:57:60:D6





Previous                                                 Next                                                 Home

No comments:

Post a Comment