Saturday, April 21, 2018

Create 'My First App' web project using eclipse

In this blog you will learn to create web project from scratch

Step 1 -  Creating Dynamic web project In Eclipse

Right Click in Project Explorer and select 
New --> Dynamic Web Project




Step 2 - Name the Project

Name the project as MyFirstApp. click on next and on last page select
Generate web.xml deployment descriptor


Step 3 - Add myFirst.jsp

Right-click on project MyFirstApp and create jsp as shown


Give name as myFirst.jsp and click on finish

Add the content to myFirst.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My First Application</title>
</head>
<body>
Welcome to My first application
</body>
</html>

Step 4 -  Edit content of web.xml

Open webContent --> web.xml
Add myFirst.jsp in welcome file list

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         id="WebApp_ID" version="3.0">
   <display-name>MyFirstApp</display-name>
   <welcome-file-list>
    <welcome-file>myFirst.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>

</web-app>

Tuesday, February 8, 2011

Encryption in PDF document with iText API


 Make PDF password protected with iText API.

1)      Encrypt existing PDF document:-
To encrypt existing document one need to create object of PdfEncryptor class.
The encrypt method of PDFEncryptor class take following parameters

Reader            : the read PDF
Output stream     : the output destination
Type              : the type of encryption. It can be one of  
  STANDARD_ENCRYPTION_40,    
  STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
User Password     : the user password.
Owner Password    : the owner password.
Permissions       : the user permissions


      public void encryptPDFFile(String sourceFilePath
, String destinationFilePath
, String userPassword
, String ownerPassword){
        try{
     PdfEncryptor.encrypt(new PdfReader(sourceFilePath)
, new FileOutputStream(destinationFilePath)
            , PdfWriter.STANDARD_ENCRYPTION_128
            , userPassword
            , ownerPassword
            , PdfWriter.ALLOW_DEGRADED_PRINTING);

  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (DocumentException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  } catch (Exception e){
    e.printStackTrace();
  }

1)      Encrypt PDF document generated form scratch:-
To encrypt generated document one have to create PdfWriter object.
Parameters required by setEncryption method of PdfWriter are

User Password     : the user password.
Owner Password    : the owner password.
Permissions       : the user permissions
Type              : the type of encryption. It can be one of 
  STANDARD_ENCRYPTION_40,   
  STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.

           Note: Need to call this method before open() method of Document object is called.

      public void encryptGeneratedPDFDocument(PdfWriter writer
                        , String userPassword, String ownerPassword)
      {
        try{
             writer.setEncryption(userPassword.getBytes()
                        ,ownerPassword.getBytes()
                        , PdfWriter.ALLOW_DEGRADED_PRINTING
                        , PdfWriter.STANDARD_ENCRYPTION_128);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
         
How to read PDF documents if documents are password protected
            1) Need to decrypt pdf
2) Read pdf document.

For that one has to use constructor of PdfReader which will take byte array of owner    
password as parameter.

      public void readEncryptedPDF(List<File> fileList
, String actualPath
, String ownerPassword){
         PdfReader reader = null;
         try{
              // If PDF document is not encrypted
              reader = new PdfReader(ff.getAbsolutePath());
         }catch (IOException io) {
              System.err.println("BAD PASSWORD EXCEPTION");

  // If PDF document is encrypted
  reader = new PdfReader(ff.getAbsolutePath()
, ownerPassword.getBytes());
         }
      }

Wednesday, January 12, 2011

OPENSSL

Openssl basics
  •       OpenSSL is an open source implementation of the SSL and TLS protocols.
  •       OpenSSL includes a command line utility that can be used to perform a variety of       cryptographic functions like digital certificates, digital signatures etc.
  •       OpenSSL is available from the OpenSSL Project at     http://www.openssl.org/

Installation and configuration
  •       Download and install latest version of openssl.
             http://www.brothersoft.com/openssl-27429.html
  •       Set PATH environmental variable to bin directory or open ‘openssl.exe’ from bin directory.
  •       Then go to the bin directory and create folder suppose name “mycerts” used to store all the created certificates.
  •       Copy ‘bin/openssl.cfg’ in ‘mycerts’ directory and rename with name suppose openssl.myca.cfg.

Steps to create digital certificates with openssl:
           
  1. create Certificate Authority’s (CA) certificate
We will use this to sign other certificate signing requests.

openssl req -config mycerts/openssl.myca.cfg -new -x509 -extensions v3_ca -keyout mycerts/myca.key -out mycerts/myca.crt -days 365

This creates a self-signed certificate with the default CA extensions which is valid for 1 year. You will be prompted for a passphrase for your CA’s private key.
And then need to provide some information about CA

            
  1. Now create user certificate and private key
             openssl req -config mycerts/openssl.myca.cfg -new -nodes -keyout mycerts/usercert1.key -out mycerts/usercert1.csr -days 365

-nodes option is needed so that private key is not protected with passphrase
Then need to provide some information about user
  1. To sign user certificate request with CA certificate
 A) Configuration required in OpenSSL to sign certificate request

Create following files in ‘bin/mycerts’ directory
    •  index.txt
    •  ca.srl  edit this file and write serial number as ‘01’
    •  Some modifications to ‘mycerts/openssl.myca.cfg’ are mandatory. Change the part underlined with red.
Default openssl.myca.cfg looks like.
 Modified openssl. myca.cfg. looks like
           
Then sign the user certificate request using modified openssl.myca.cfg with following command.

openssl ca -config mycerts/openssl.myca.cfg -policy policy_anything -out mycerts/usercert1.crt -infiles mycerts/usercert1.csr

  1. To convert .crt  format to PKCS12 (.p12)format
To include the entire certificate chain of the certificate include -chain option and provide path for CA certificate file.

openssl pkcs12 -export -chain -in mycerts/usercert1.crt -inkey mycerts/usercert1.key -out mycerts/usercert1.p12 -CAfile mycerts/myca.crt

  1. To add certificate chaining in  java .keystore
JKS conversion using jetty
A)    Download jetty.jar from

B)     Save it on drive suppose C:\conversion

C)    Place your PKCS12 format file in same folder

D)    Now open command prompt for that directory

E)     Run following command to import certificate chaining in jks
Enter the password for containing file and output the keystore as requested

java -classpath .;org.mortbay.jetty.jar org.mortbay.util.PKCS12Import usercert1.p12 mynewjks.jks

  1. To revoke user certificate
 A.     Configuration required in OpenSSL to revoke user
       Create file crl.srl under mycerts directory.
       crl.srl edit this file and write serial number as ‘01’
                                                       Some modifications in openssl.myca.cfg are mandatory 

         B.     Revoke user certificate 
       openssl ca -config mycerts/openssl.myca.cfg -revoke 
       mycerts/usercert1.crt
   

        C.     Then generate CRL
      openssl ca -config mycerts/openssl.myca.cfg -gencrl -out 
      mycerts/myca.crl
   
Reference : 

Tuesday, November 23, 2010

Siging text through javascript

<html>
<head>
    <script type="text/javascript">
        function signDigest(text)
        {
        if(window.event)
        window.event.cancelBubble = true;

       
        var dest = sign(text); //TODO
        //alert(dest);
        document.getElementById('signtxt').value = dest;
       
        return dest;
        }

        // CAPICOM constants
        var CAPICOM_STORE_OPEN_READ_ONLY = 0;
        var CAPICOM_CURRENT_USER_STORE = 2;
        var CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
        var CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
        var CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
        var CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
        var CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 0x00000080;
        var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
        var CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0;
        var CAPICOM_ENCODE_BASE64 = 0;
        var CAPICOM_E_CANCELLED = -2138568446;
        var CERT_KEY_SPEC_PROP_ID = 6;

        function IsCAPICOMInstalled()
        {
        if(typeof(oCAPICOM) == "object")
        {
        if( (oCAPICOM.object != null) )
        {
        // We found CAPICOM!
        return true;
        }
        }
        }

        function FindCertificateByHash()
        {

        try
        {
        // instantiate the CAPICOM objects
        var MyStore = new ActiveXObject("CAPICOM.Store");
        // open the current users personal certificate store
        MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);

        // find all of the certificates that have the specified hash
        var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, strUserCertigicateThumbprint);

        var Signer = new ActiveXObject("CAPICOM.Signer");
        Signer.Certificate = FilteredCertificates.Item(1);
        return Signer;

        // Clean Up
        MyStore = null;
        FilteredCertificates = null;
        }
        catch (e)
        {
        if (e.number != CAPICOM_E_CANCELLED)
        {
        return new ActiveXObject("CAPICOM.Signer");
        }
        }
        }

        function sign(src)
        {
        if(window.crypto && window.crypto.signText)
        return sign_NS(src);

        return sign_IE(src);
        }

        function sign_NS(src)
        {
        alert(crypto);
        var s = crypto.signText(src, "ask" );
        return s;
        }

    function sign_IE(src)
    {
    try
    {
    // instantiate the CAPICOM objects
    var SignedData = new ActiveXObject("CAPICOM.SignedData");
    var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");

    // Set the data that we want to sign
    SignedData.Content = src;
    var Signer = FindCertificateByHash();

    // Set the time in which we are applying the signature
    var Today = new Date();
    TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
    TimeAttribute.Value = Today.getVarDate();
    Today = null;
    Signer.AuthenticatedAttributes.Add(TimeAttribute);

    // Do the Sign operation
    var szSignature = SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);
    return szSignature;
    }
    catch (e)
    {
    if (e.number != CAPICOM_E_CANCELLED)
    {
    alert("An error occurred when attempting to sign the content, the errot was: " + e.description);
    }
    }
    return "";
    }
</script>
</head>
<body>
<input id="text" type="text"/>
<input type="hidden" name="hidn" value="HiddenValue"/>
<textarea style="width:250px;height:100px;" id="signtxt"></textarea>
<input onclick="signDigest(document.getElementById('text').value);" type="button" value="Sign" />
 <OBJECT id="oCAPICOM" codeBase="capicom.cab" classid="clsid:A996E48C-D3DC-4244-89F7-AFA33EC60679" VIEWASTEXT/>
</body>
</html>