Wednesday, 14 February 2018

Get x.509 certificate from encoded string

Step 1: Decode the encoded string.

Decoder decoder = Base64.getDecoder();
byte[] decodedData = decoder.decode(encodedString);

Step 2: Get input stream from decoded data.
InputStream inputStream = new ByteArrayInputStream(decodedData)

Step 3: Generate certificate from decoded data.
CertificateFactory cf = CertificateFactory.getInstance("X.509");

java.security.cert.Certificate certificate = cf.generateCertificate(inputStream);

if (certificate instanceof X509Certificate) {
         return (X509Certificate) certificate;
}

Find the below working application.

CertificateUtil.java
package com.sample.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Base64.Decoder;;

public class CertificateUtil {
 /**
  * 
  * @param encodedString
  *            base64 encoded string
  * 
  * @return X509Certificate from the encodedString, null on failure cases
  */
 public static X509Certificate getX509Certificate(String encodedString) {
  if (encodedString == null) {
   return null;
  }

  Decoder decoder = Base64.getDecoder();
  byte[] decodedData = decoder.decode(encodedString);

  try (InputStream inputStream = new ByteArrayInputStream(decodedData)) {
   CertificateFactory cf = CertificateFactory.getInstance("X.509");

   java.security.cert.Certificate certificate = cf.generateCertificate(inputStream);

   if (certificate instanceof X509Certificate) {
    return (X509Certificate) certificate;
   }

  } catch (Exception e) {
   e.printStackTrace();
  }

  return null;

 }
}

Test.java
package com.sample.test;

import java.security.cert.X509Certificate;

import com.sample.util.CertificateUtil;

public class Test {
 
 public static void main(String args[]) throws Exception {
  String encodedString = "MIIDbTCCAlWgAwIBAgIEHUj86jANBgkqhkiG9w0BAQsFADBnMQswCQYDVQQGEwJrcjEQMA4GA1UECBMHa3Jpc2huYTEQMA4GA1UEBxMHa3Jpc2huYTEQMA4GA1UEChMHa3Jpc2huYTEQMA4GA1UECxMHa3Jpc2huYTEQMA4GA1UEAxMHa3Jpc2huYTAeFw0xODAyMDkwNDEwMjJaFw0xOTAyMDkwNDEwMjJaMGcxCzAJBgNVBAYTAmtyMRAwDgYDVQQIEwdrcmlzaG5hMRAwDgYDVQQHEwdrcmlzaG5hMRAwDgYDVQQKEwdrcmlzaG5hMRAwDgYDVQQLEwdrcmlzaG5hMRAwDgYDVQQDEwdrcmlzaG5hMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqoDP8q/LerAIb6WBx0nx3i670p7uwRbTQ/NeK54BEsV3pkjT8GlPsTP2ai6Xs038oYkgSxldlfhgpdXsWqh95+YdqDPJV2iF4LAET2Z9qrUChp6MkmHQr8HRi1+2UOS6WI0IX4fZasXapL1cQCsGTYem1b4kJmYPXczhtOMKwJXbdA0YvzE+4m2pX1wjMufi2eX8a4quojQjJrURnq74/XJepNnA0yWRuczdLG3XpPFftQaCiAj+Oa/3bKUYXRg1ODdl5VTaxUkqL/2odw4vvFs2fhSnouALsc+wyAKaBH38ZICUCoSiX6mU9hCvBpbHFk6ToQcPTo3CkWGSzBiPrQIDAQABoyEwHzAdBgNVHQ4EFgQUT1S1ED2sUYPCi8Thmz/tEqiSLIIwDQYJKoZIhvcNAQELBQADggEBAKabXk+LifQMnA8eJvDkn8xZ3FKr/9osmIcJjkO4i0vtnGOSxQ4+IyATxJ/4nrXAZwBI4+q4l13GNFw+S6ebKoYfNWEvZHUbjLALr98+nhHsURY73TIV2nw75bWOvh3QRpDDPiP/3Fzs9XjENxeUXcUV+mLGETKGa6szfcZ0Huaeva5nxDt7U+4/3xyMO9CWuYglhC8act1pd3RfZdZJaDN3fUy/+tocKXMmo0s7oLiAlyfLNhng2aqHwHu/sAoHjYyLhqz7401MmqHYX8hkOJ6FBXjJZz62zfrFUVoM10zNkByIbdL4WzNf/d8z0X57IgHg08IPpYJOfenSIqF3Rmo=";
  X509Certificate x509Certificate = CertificateUtil.getX509Certificate(encodedString);
  
  System.out.println("Issuer Name : " + x509Certificate.getIssuerX500Principal());
  
 }
}

Output
Issuer Name : CN=krishna, OU=krishna, O=krishna, L=krishna, ST=krishna, C=kr


Kotlin: Data Classes: copy function

By default, Kotlin data class generate copy function. By using copy function, we can copy data object by altering some of its properties.

         var employee1 = Employee("Krishna", "Gurram", "India")
         var employee2 = employee1.copy(firstName = "Chamu")

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var country: String)

fun main(args: Array<String>) {
 var employee1 = Employee("Krishna", "Gurram", "India")
 var employee2 = employee1.copy(firstName = "Chamu")

 println("employee1 : $employee1")
 println("employee2 : $employee2")
}

Output
employee1 : Employee(firstName=Krishna, lastName=Gurram, country=India)
employee2 : Employee(firstName=Chamu, lastName=Gurram, country=India)


Can I provide explicit implementation of copy function?
No, it is not allowed.




Previous                                                 Next                                                 Home

Monday, 12 February 2018

Kotlin: Data classes

Data classes are special kind of classes in kotlin, their main purpose is to hold the data.

Kotlin derives below members for the data classes.

a.   equals()/hashCode() pair
b.   toString() of the form "User(name=John, age=42)"
c.   componentN() functions corresponding to the properties in their order of declaration
d.   copy().

How to define data class?
By using the keyword ‘data’ we can define data classes.

Syntax
data class ClassName(memberVariables)

Ex
data class Employee(var firstName: String, var lastName: String, var id: Int)

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var id: Int)

fun main(args: Array<String>) {
 var obj = Employee("Krishna", "Gurram", 1)

 var firstName = obj.firstName;
 var lastName = obj.lastName
 var id = obj.id

 println("First Name : $firstName")
 println("Last Name : $lastName")
 println("Id : $id")

}

Output

First Name : Krishna
Last Name : Gurram
Id : 1

Is there any constraints while defining data classes?
Yes, below constraint are applied while defining data classes.

a.   The primary constructor needs to have at least one parameter
b.   All primary constructor parameters need to be marked as val or var
c.   Data classes cannot be abstract, open, sealed or inner

d.   Data classes may only implement interfaces.






Previous                                                 Next                                                 Home

Saturday, 10 February 2018

Kotlin: Overriding extensions

In kotlin, you can override extensions. To override extension defined in class ‘B’, from class ‘C’, the extension should be defined with ‘open’ in class ‘B’.

Find the below working application.

Test.kt
package com.sample.test

class A {
 fun sayHello() {
  println("Hello")
 }
}

open class B {
 open fun A.sayWelcome() {
  println("Welcome defined in class B")
 }

 fun welcomeUser() {
  var obj = A()
  obj.sayWelcome()
 }
}

class C : B() {
 override fun A.sayWelcome() {
  println("Welcome defined in class C")
 }
}

fun main(args: Array<String>) {
 var bObj = B()
 var cObj = C()

 bObj.welcomeUser()
 cObj.welcomeUser()
}

Output
Welcome defined in class B
Welcome defined in class C






Previous                                                 Next                                                 Home

How to set proxy settings for https, http communication


You should set below system properties for https communication.
         https.proxyHost
https.proxyPort

You should set below system properties for http communication.
         http.proxyHost
http.proxyPort

Example
String hostName = "";
String port = "";

System.setProperty("https.proxyHost", hostName);
System.setProperty("https.proxyPort", port);


You may like

Convert base64 encoded string to certificate

In my previous post, I explained how to convert the certificate to base64 encoded string. In this post, I am going to show you how to convert the encoded string to certificate.

It is very simple, just decode the encoded string and write the encoded string to the file.

Test.java
package com.sample.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Decoder;

public class Test {
 private static final String certificateFilePath = "C:\\Users\\krishna\\myCertificate.cer";

 public static void writeBytesToFile(String encodedString, String certificateFilePath)
   throws FileNotFoundException, IOException {
  byte[] encodedBytes = encodedString.getBytes();
  Decoder decoder = Base64.getDecoder();
  byte[] decodedBytes = decoder.decode(encodedBytes);

  try (FileOutputStream fos = new FileOutputStream(certificateFilePath)) {
   fos.write(decodedBytes);
  }
 }

 public static void main(String args[]) throws Exception {
  String encodedString = "MIIDbTCCAlWgAwIBAgIEHUj86jANBgkqhkiG9w0BAQsFADBnMQswCQYDVQQGEwJrcjEQMA4GA1UECBMHa3Jpc2huYTEQMA4GA1UEBxMHa3Jpc2huYTEQMA4GA1UEChMHa3Jpc2huYTEQMA4GA1UECxMHa3Jpc2huYTEQMA4GA1UEAxMHa3Jpc2huYTAeFw0xODAyMDkwNDEwMjJaFw0xOTAyMDkwNDEwMjJaMGcxCzAJBgNVBAYTAmtyMRAwDgYDVQQIEwdrcmlzaG5hMRAwDgYDVQQHEwdrcmlzaG5hMRAwDgYDVQQKEwdrcmlzaG5hMRAwDgYDVQQLEwdrcmlzaG5hMRAwDgYDVQQDEwdrcmlzaG5hMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqoDP8q/LerAIb6WBx0nx3i670p7uwRbTQ/NeK54BEsV3pkjT8GlPsTP2ai6Xs038oYkgSxldlfhgpdXsWqh95+YdqDPJV2iF4LAET2Z9qrUChp6MkmHQr8HRi1+2UOS6WI0IX4fZasXapL1cQCsGTYem1b4kJmYPXczhtOMKwJXbdA0YvzE+4m2pX1wjMufi2eX8a4quojQjJrURnq74/XJepNnA0yWRuczdLG3XpPFftQaCiAj+Oa/3bKUYXRg1ODdl5VTaxUkqL/2odw4vvFs2fhSnouALsc+wyAKaBH38ZICUCoSiX6mU9hCvBpbHFk6ToQcPTo3CkWGSzBiPrQIDAQABoyEwHzAdBgNVHQ4EFgQUT1S1ED2sUYPCi8Thmz/tEqiSLIIwDQYJKoZIhvcNAQELBQADggEBAKabXk+LifQMnA8eJvDkn8xZ3FKr/9osmIcJjkO4i0vtnGOSxQ4+IyATxJ/4nrXAZwBI4+q4l13GNFw+S6ebKoYfNWEvZHUbjLALr98+nhHsURY73TIV2nw75bWOvh3QRpDDPiP/3Fzs9XjENxeUXcUV+mLGETKGa6szfcZ0Huaeva5nxDt7U+4/3xyMO9CWuYglhC8act1pd3RfZdZJaDN3fUy/+tocKXMmo0s7oLiAlyfLNhng2aqHwHu/sAoHjYyLhqz7401MmqHYX8hkOJ6FBXjJZz62zfrFUVoM10zNkByIbdL4WzNf/d8z0X57IgHg08IPpYJOfenSIqF3Rmo=";
  writeBytesToFile(encodedString, certificateFilePath);
 }
}

When you ran above application, you can able to see below certificate.

You may like


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.convertCertificateToString(certificateFilePath);
  
  System.out.println(certificateInfo);
 }
}

Output
MIIDbTCCAlWgAwIBAgIEHUj86jANBgkqhkiG9w0BAQsFADBnMQswCQYDVQQGEwJrcjEQMA4GA1UECBMHa3Jpc2huYTEQMA4GA1UEBxMHa3Jpc2huYTEQMA4GA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