Skip to main content

Java Signature Certificate




Signature
A valid digital signature gives a recipient reason to believe that the message was created by a known sender (authentication), that the sender cannot deny having sent the message (non-repudiation), and that the message was not altered in transit (integrity)




 Original-data.getByte() + private key à signature


All are in byte array
As signature has to be passed through network, we convert into string but we cant use just string of original byte array because of security. Hence we do manipulation of byte array and convert into a different string.
We shoud not send new String(byte [] signature), we should send  new String(Base64.encode(byte[] signature))


Verification:
Client send (new data + signature)

object{
User name: Ram
Id : 678
Signature : ZTngSmnSpmWIj40r5TQ1hmec0UbfJLSCRSxbVBxCwchcFu6A8RS+O9BUFgG7U+UozVlrO5xGl9tARHxcIK4y2x/UHvhfYu74SOq22XgdGNuPMGQ560pUpiSkXspfGuFh9xHqovNGs7MQvWyESgurqehdsFD18sXV0z7gnqqFm78=
}

Server will receive new data and then again calculate a signature internally  and then it matches with th received signature.

Generate signature:
Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initSign(certDetails.getPrivateKey());

            // Supply the data to be signed to the Signature object
            // using the update() method and generate the digital
            // signature.
            byte[] databytes = Files.readAllBytes(Paths.get("D:\\user.txt"));
            signature.update(databytes);
            byte[] digitalSignature = signature.sign();

            // Save digital signature and the public key to a file.
            //Files.write(Paths.get("D:\\signature.txt"), digitalSignature);
            System.out.println(new String(Base64.encodeBase64(digitalSignature)));

Verify :
Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initVerify(publicKey);

            byte[] bytes = Files.readAllBytes(Paths.get("D:\\test1.txt"));
            signature.update(bytes);

            boolean verified = signature.verify(digitalSignature);







Java program :

package com.crypto.Digital;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.swing.JOptionPane;

import org.apache.commons.codec.binary.Base64;

public class GenerateDigitalSignature {
    public static void main(String[] args) {
        try {
           
            CertificateDetails certDetails = CertificateUtil.getCertificateDetails("d:\\test.keystore", "changeit");
            System.out.println(certDetails.getPrivateKey());
            System.out.println(certDetails.getX509Certificate());
           


            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initSign(certDetails.getPrivateKey());

.
            byte[] bytes = Files.readAllBytes(Paths.get("D:\\test.txt"));
            signature.update(bytes);
            byte[] digitalSignature = signature.sign();
            System.out.println(new String(Base64.encodeBase64(digitalSignature)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.crypto.Digital;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

import javax.swing.JOptionPane;

import org.apache.commons.codec.binary.Base64;

public class VerifyDigitalSignature {
    public static void main(String[] args) {
        try {
            String digitalSignature1 = JOptionPane.showInputDialog("Type your signature here");
            byte[] digitalSignature =  Base64.decodeBase64(digitalSignature1.getBytes());
           
            CertificateDetails certDetails = CertificateUtil.getCertificateDetails("d:\\test.keystore", "changeit");
            System.out.println(certDetails.getPrivateKey());
            System.out.println(certDetails.getX509Certificate());

            PublicKey publicKey = certDetails.getX509Certificate().getPublicKey();
            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initVerify(publicKey);

            byte[] bytes = Files.readAllBytes(Paths.get("D:\\test1.txt"));
            signature.update(bytes);

            boolean verified = signature.verify(digitalSignature);
            if (verified) {
                System.out.println("Data verified.");
            } else {
                System.out.println("Cannot verify data.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}






Geneate certificate and private key and put into JKS from program

note : With out program, we use keytool.


package com.crypto.Digital;

import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Date;
import sun.security.x509.CertAndKeyGen;
import sun.security.x509.X500Name;

public class GenBothCertificateAndPrivateKey {
      
        private static final int keysize = 1024;
        private static final String commonName = "www.test.de";
        private static final String organizationalUnit = "IT";
        private static final String organization = "test";
        private static final String city = "test";
        private static final String state = "test";
        private static final String country = "DE";
        private static final long validity = 1096; // 3 years
        private static final String alias = "tomcat";
        private static final char[] keyPass = "changeit".toCharArray();

        // copied most ideas from sun.security.tools.KeyTool.java

        @SuppressWarnings("restriction")
        public static void main(String[] args) throws Exception {

            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(null, null);

            CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);

            X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);

            keypair.generate(keysize);
            PrivateKey privKey = keypair.getPrivateKey();

            X509Certificate[] chain = new X509Certificate[1];

            chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);

            keyStore.setKeyEntry(alias, privKey, keyPass, chain);

            keyStore.store(new FileOutputStream("d:\\test.keystore"), keyPass);
           
            //Files.write(Paths.get("D:\\PrivateKeyTest.txt"), privKey.getEncoded());


        }

}
--------------------------------------------------------




Comments

Popular posts from this blog

Camunda Spring Boot with Shared Engine with War file

This is the only one website (may be first) to show an example to create working war file for camunda shared engine using Spring Boot. We analysed the problem using pure spring boot "starter" dependencies that it contains camunda engine plus tomcat, so even when you remove tomcat using either <provided> or <exclude>, it continues to run on tomcat as its already with in camunda engine. And when you try to create war file and paste in into shared camunda engine outside then that war will no work. This is because that war you created containing camunda engine and a tomcat inside it and when you paste into another outside camunda engine, it gets confused to which camunda to use. Hence I worked on this and brought a mix version of spring and spring boot implementation of camunda. So here you go....and thanks me later :) Here is the pom file -------------------------------------------------------------------------------------------- <?xml version=...

Introduction to Reactive Programming in Java with Project Reactor

Introduction to Reactive Programming in Java with Project Reactor we will go through below: 1. Introduction to Reactive Programming What is reactive programming? Key principles of reactive systems: Responsive : Systems should respond in a timely manner. Resilient : Systems should be fault-tolerant. Elastic : Systems should scale as needed. Message-driven : Systems should use asynchronous messaging. Comparison between imperative programming and reactive programming. 2. Understanding Reactive Streams Publisher , Subscriber , Subscription , and Processor interfaces. The four key signals: onNext() , onComplete() , onError() , and onSubscribe() . Backpressure handling in reactive systems. 3. Introduction to Project Reactor What is Project Reactor? Key classes: Mono and Flux . Mono : Represents 0 or 1 item. Flux : Represents 0 to N items. Non-blocking nature and how it helps in building scalable systems. 4. Building a Reactive Application with Project Reactor Demonstrating how to use Mono ...

Hibernate interview questions

Question : Why JPA Entity or Hibernate Persistence Class Should Not be Final?  Answer : One of the interesting hibernate interview questions is, why you should not make a Hibernate persistent class final? I'll try to answer this question in this short blog post. The use of proxies is the core feature of Hibernate (one of the most popular ORM frameworks for Java Projects) for implementing key performance features e.g. lazy loading and lazy associations fetching. In order to use a proxy in place of a real class, your hibernate persistence class must be either non-final or the implementation of an interface that declares all of the public methods. Difference between save vs persist and saveOrUpdate in Hibernate Save vs. saveOrUpdate vs. persist in Hibernate? What is the difference between save and saveOrUpdate or Difference between saving and persist are common interview question in any Hibernate interview, much like the difference between get and load method in Hibernate. H...