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=&

Stream flatMap() in Java with examples

Stream flatMap() in Java with examples Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an  intermediate operation . These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output. Note :  Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead. flatMap() V/s map()  : 1) map() takes a Stream and transform it to another Stream. It applies a function on each element of Stream and store return value into new Stream. It does not flatten the stream. But flatMap() is the combination of a map and a flat operation i.e, it applies a function to elements as well as flatten them. 2) map() is used for