Wednesday, 12 July 2017

How to generate Certificate in Java


How to create a certificate from Keypair of issuer and subject?

Create w a two X500Name objects one for isuer and one for subject.



1
2
3
4
5
6
7
8
9
X500Name issuer = new X500Name(IETFUtils.rDNsFromString("C=rootca,OU=rootca,O=Thawate", RFC4519Style.INSTANCE));
X500Name subject = new X500Name(IETFUtils.rDNsFromString("C=company,OU=12345,O=Organization", RFC4519Style.INSTANCE));X509CertificateObject cert1 = generateCert("company", companyKeypair, false, caKeypair.getPublic(), caKeypair.getPrivate(),issuer,subject);
Certificate[] certChain = new Certificate[1];  
certChain[0] = (Certificate) cert1;  
ks.setKeyEntry("identity", (Key)companyKeypair.getPrivate(), ksPass, certChain); 
  

call below method as shown above.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
 private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey,X500Name issuer,X500Name subject)
      throws IOException, CertIOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException {
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.DAY_OF_YEAR, 10);

    BigInteger serialNumber = BigInteger.valueOf((startDate.getTimeInMillis()));
    
    JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate.getTime(), endDate.getTime(), subject, kp.getPublic());
    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    certGen.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority));
    certGen.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
    if (isCertAuthority) {
      certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    }
    X509CertificateHolder cert = certGen.build(new JcaContentSignerBuilder("MD5withRSA").build(signerPrivateKey));
    return new X509CertificateObject(cert.toASN1Structure());
  }

Friday, 5 May 2017

SoftHSM2 in java


Challenge:
how to work with softhsm2 in java ?

Solution:

1. Download  .msi installer from  softhsm2 windows installer.
2.  Execute below script to initialize Tokens .

 Microsoft Windows [Version 10.0.14393]
    (c) 2016 Microsoft Corporation. All rights reserved.

    C:\WINDOWS\system32>cd\

    C:\>cd SoftHSM2

    C:\SoftHSM2>cd bin

    C:\SoftHSM2\bin>softhsm2-util.exe --init-token --slot 0 --label "My token 1"
    === SO PIN (4-255 characters) ===
    Please enter SO PIN:
    ERROR: The length of the PIN is out of range.
    === SO PIN (4-255 characters) ===
    ^C
    C:\SoftHSM2\bin>softhsm2-util.exe --init-token --slot 0 --label "My token 1"
    === SO PIN (4-255 characters) ===
    Please enter SO PIN: ****
    Please reenter SO PIN: ****
    === User PIN (4-255 characters) ===
    Please enter user PIN: ****
    Please reenter user PIN: ****
    CKR_SLOT_ID_INVALID: Slot 0 does not exist.

    C:\SoftHSM2\bin>softhsm2-util.exe --show-slots
    Available slots:
    Slot 1526831955
        Slot info:
            Description:      SoftHSM slot ID 0x5b019b53
            Manufacturer ID:  SoftHSM project
            Hardware version: 2.2
            Firmware version: 2.2
            Token present:    yes
        Token info:
            Manufacturer ID:  SoftHSM project
            Model:            SoftHSM v2
            Hardware version: 2.2
            Firmware version: 2.2
            Serial number:    cafa9efc5b019b53
            Initialized:      yes
            User PIN init.:   yes
            Label:            0 token
    Slot 1
        Slot info:
            Description:      SoftHSM slot ID 0x1
            Manufacturer ID:  SoftHSM project
            Hardware version: 2.2
            Firmware version: 2.2
            Token present:    yes
        Token info:
            Manufacturer ID:  SoftHSM project
            Model:            SoftHSM v2
            Hardware version: 2.2
            Firmware version: 2.2
            Serial number:
            Initialized:      no
            User PIN init.:   no
            Label:

    C:\SoftHSM2\bin>softhsm2-util.exe --init-token --slot 1 --label "My token 1"
    === SO PIN (4-255 characters) ===
    Please enter SO PIN: ****
    Please reenter SO PIN: ****
    === User PIN (4-255 characters) ===
    Please enter user PIN: ****
    Please reenter user PIN: ****
    The token has been initialized.

    C:\SoftHSM2\bin>softhsm2-util.exe --show-slots
    Available slots:
    Slot 1242738572
        Slot info:
            Description:      SoftHSM slot ID 0x4a12af8c
            Manufacturer ID:  SoftHSM project
            Hardware version: 2.2
            Firmware version: 2.2
            Token present:    yes
        Token info:
            Manufacturer ID:  SoftHSM project
            Model:            SoftHSM v2
            Hardware version: 2.2
            Firmware version: 2.2
            Serial number:    00fbfb20ca12af8c
            Initialized:      yes
            User PIN init.:   yes
            Label:            My token 1
    Slot 1526831955
        Slot info:
            Description:      SoftHSM slot ID 0x5b019b53
            Manufacturer ID:  SoftHSM project
            Hardware version: 2.2
            Firmware version: 2.2
            Token present:    yes
        Token info:
            Manufacturer ID:  SoftHSM project
            Model:            SoftHSM v2
            Hardware version: 2.2
            Firmware version: 2.2
            Serial number:    cafa9efc5b019b53
            Initialized:      yes
            User PIN init.:   yes
            Label:            0 token
    Slot 2
        Slot info:
            Description:      SoftHSM slot ID 0x2
            Manufacturer ID:  SoftHSM project
            Hardware version: 2.2
            Firmware version: 2.2
            Token present:    yes
        Token info:
            Manufacturer ID:  SoftHSM project
            Model:            SoftHSM v2
            Hardware version: 2.2
            Firmware version: 2.2
            Serial number:
            Initialized:      no
            User PIN init.:   no
            Label:

    C:\SoftHSM2\bin>softhsm2-util.exe --init-token --slot 2 --label "My token 2"
    === SO PIN (4-255 characters) ===
    Please enter SO PIN: ****
    Please reenter SO PIN: ****
    === User PIN (4-255 characters) ===
    Please enter user PIN: ****
    Please reenter user PIN: ****
    The token has been initialized.

    C:\SoftHSM2\bin

Run the below Java Code to access hsm from java .




 1
   import java.security.Key;
    import java.security.KeyStore;
    import java.security.Provider;
    import java.security.Security;

    import javax.crypto.spec.SecretKeySpec;

    import sun.security.pkcs11.SunPKCS11;

    public class TestClass {


         public static void main(String[] args) throws Exception {
                // Set up the Sun PKCS 11 provider
               // String configName = "Z:\\SOFTHSM_INSTALL\\etc\\softhsm2.conf";

             String configName = "softhsm2.cfg";

                Provider p = new SunPKCS11(configName);

                if (-1 == Security.addProvider(p)) {
                    throw new RuntimeException("could not add security provider");
                }

                // Load the key store
                char[] pin = "mypin".toCharArray();
                KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
                keyStore.load(null, pin);

                // AES key
                SecretKeySpec secretKeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES");
                Key key = new SecretKeySpec(secretKeySpec.getEncoded(), "AES");

                keyStore.setKeyEntry("AA", key, "1234".toCharArray(), null);
                keyStore.store(null); //this gives me the exception.

         }

    }



Tuesday, 18 April 2017

Java Threads Issues

Question:
Sometimes threads are not closed or reused by the pool created by ExecutorService.newCachedThread()


Answer:
Don't Rename any of the threads after created , if you do so it will not manged/closed  by Pool . So becareful while doing Thread.currentThread().setName("NEW NAME")

Wednesday, 22 March 2017

How to run Karaf as Apache Commons Daemon Service


How to run Karaf as Service with Apache Commons Daemon ?


### How do I get set up? ###


YOu Can change All Your Service Names in Install-Karaf-Service.bat.
If you want to change exe name then change in all batch files.


### How to run with Latest Karaf ###

Download Fresh Karaf Zip from Karaf Site.
Copy All exe and bat files into Karaf Root folder.

Now go to Command prompt
karaf-4.0.8>Install-Karaf-Service.bat

Now you can verify in Windows Service with name "Karaf Daemon Service"

For Uninstalling Service ::::
karaf-4.0.8>Uninstall-Karaf-Service.bat
Deleted KARAF Successfully
Press any key to continue . . .

###  Which Architecture it Supports ###

Currently Exe I provided are amd64 because mine is 64-bit Machine. You can download 32-bit from Apache Commons Daemon Website .


Repository Details


Monday, 13 March 2017

Gradle Tips in Eclipse And Syntax Highlight

Q. How use Gradle Project Nature in Eclipe?
A: Use Gradle BuildShip Plugin in Eclipse provided by VMWare . It comes with Elephant Symbol.

Q: Can we get Gradle Syntax Highlight in for gradle files in Eclipse?
A; Use Gradle MinimalList Plugin from Eclipse Market. "minimalist gradle editor".

After installing above you can see build.gradle with syntax highlighting.
If not rightClick on Gradle File>Openwith>Minimalist Gradle.




Thursday, 17 November 2016

Gradle Signing Jar File

Problem:
How to sign jar file in gradle , same like jarsigner command line tool ?

Solution:
 we can make use of AntBuilder of Gradle (which is inherited from AntBuilder <- Groovy).
Gradle supports all ant tasks in build file with ease.

You can add task extension to jar task like this.

  jar.doLast {
         new File('build/sign').mkdirs();
         ant.signjar(
         destDir: 'build/sign',
         jar: 'build/libs/*.jar',
         alias:"anyAlias",
         storetype:"jks",
         keystore:"keystore.jks",
         storepass:"keystore_password",
         preservelastmodified:"true")
  }


Now if run below command u will see singed jar file in build/sign directory, but you have to create keystore before running gradle command and copy to root project directory.

>gradle clean jar