Showing posts with label base64. Show all posts
Showing posts with label base64. Show all posts

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

Tuesday, 6 March 2018

Base64 encoding and decoding in Java

In this post, you are going to learn below things.
a.   What is Base64 Encoding/decoding
b.   How to encode data in Base64
c.   Where can I use Base64 encoding
d.   How much more memory base-64 require to represent the data?
e.   How can I perform base64 encoding in Java?

What is Base64 encoding/decoding?
Base64 is one of binary-to-text encoding scheme. In binary-to-text encoding, we encode binary data in plain text.

Below tables summarizes all the symbols in base64 scheme.

Value
Char
Value
Char
Value
Char
Value
Char
0
A
16
Q
32
g
48
w
1
B
17
R
33
h
49
x
2
C
18
S
34
i
50
y
3
D
19
T
35
j
51
z
4
E
20
U
36
k
52
0
5
F
21
V
37
l
53
1
6
G
22
W
38
m
54
2
7
H
23
X
39
n
55
3
8
I
24
Y
40
o
56
4
9
J
25
Z
41
p
57
5
10
K
26
a
42
q
58
6
11
L
27
b
43
r
59
7
12
M
28
c
44
s
60
8
13
N
29
d
45
t
61
9
14
O
30
e
46
u
62
+
15
P
31
f
47
v
63
/

Output Padding
Each base-64 encoded digit is represented by 6 bits. When data is not split exactly by 6 bits, then padding needs to be done. Data can be padded by ‘==’ (or) =.

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

How to encode data in Base-64?
Let me explain with an example, how the string "java" is represented in Base64 encoding scheme.

"java" represented in ASCII form like below.
01101010011000010111011001100001

Since base64 encoding scheme requires 6 bits to represent a character, divide the above binary information into 6 bits groups from left to right.

011010   100110   000101   110110   011000   01
   26          38           5           54          24
   a            m            F           2            Y

As you see, above example, last group data is not split exactly by 6 bits. We end up with 2 bits. To make it 6 bits, we need to pad 4 0's at end.

011010   100110   000101   110110    011000   010000
   26          38           5           54           24          16
   a            m            F           2             Y            Q
  
Since last group contain only one byte (01, before adding 0000), we need to pad the encoded information with '=='.

So final encoded value is amF2YQ==.

Where can I use Base64 encoding?
It is used, when you want to transfer some binary information over network and network is not supporting transfer of binary information, you can encode the binary data using Base-64 and transfer over the network.

How much more memory base-64 require to represent the data?
Base-64 maps 3 bytes (8 x 3 = 24 bits) in 4 Base-64 characters (6 x 4 = 24 bits). Therefore it requires 4/3 = 1.3333333 times the original. So Base64 encoding uses 33% more storage.

How can I perform base64 encoding in Java?
'java.util.Base64' class provides functionality to encode and decode the information.

How to get Base64 Encoder?
Encoder encoder = Base64.getEncoder();

How to get Base64 Decoder?
Decoder decoder = Base64.getDecoder();

Find the below working application.
Test.java
package com.sample.test;

import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

public class Test {
 public static void main(String args[]) {
  Encoder encoder = Base64.getEncoder();
  Decoder decoder = Base64.getDecoder();

  String originalData = "java";
  byte[] encodedBytes = encoder.encode(originalData.getBytes());
  String encodedStr = new String(encodedBytes);

  byte[] decodedBytes = decoder.decode(encodedBytes);
  String decodedStr = new String(decodedBytes);

  System.out.println("Original Data is : " + originalData);
  System.out.println("Encoded Data is : " + encodedStr);
  System.out.println("Decoded data is : " + decodedStr);

 }
}

Output
Original Data is : java
Encoded Data is : amF2YQ==
Decoded data is : java