Tuesday, 28 February 2023

Create and use self-signed SSL Certificate with Apache

Create and use self-signed SSL Certificate with Apache

PDF
A self-signed SSL Certificate can be used for testing purposes or on websites where the visitors are people who know you and trust you. For situations where you ask for credit card or other payment information I strongly advice you to use a signed certificate (Make sure openssl is installed on your system, on a typically installation of CentOs it is installed by default) The first step is to generate the private key:
openssl genrsa -des3 -out server.key 1024
You will be asked for a password twice. Make it a stong password and don't forget this it. Once the private key has been generated you have to generate Certificate Signing Request
openssl req -new -key server.key -out server.csr
This will ask you serveral questions:
Country Name (2 letter code) [GB]:
State or Province Name (full name) [Berkshire]:
Locality Name (eg, city) [Newbury]:
Organization Name (eg, company) [My Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []: FQDN of the server
Email Address []: myaddress at mydomain.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Make sure that the Common Name matches the Fully Qualified DomainName of your SSL website.
As we signed the key with a password we should remove it, otherwise Apache cann't start up withou prompting for this password. We can remove the password:
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
Generate the cerficate which will be valid for 365 days:
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Last step is to configure Apache to use the self-signed certificate. Make sure the mod_ssl is enabled in your config. Open /etc/httpd/conf/httpd.conf find and uncomment by removing the # in the line:
# LoadModule ssl_module modules/mod_ssl.so
Copy the certificate and the private key to the Apache conf directory:
cp server.crt /etc/httpd/conf/ssl/server.crt
cp server.key /etc/httpd/conf/ssl/server.key
Now edit the directive in your config matching the server you created this certificate for and add:
SSLEngine on
SSLCertificateFile /usr/local/apache/conf/ssl.crt/server.crt
SSLCertificateKeyFile /usr/local/apache/conf/ssl.key/server.key
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
CustomLog logs/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
and restart Apache:
/etc/init.d/apache restart

Spring Security Concept and end to end implementation example

 What is Spring Security?


Spring Security is a widely used and highly customizable security framework for Java-based applications. It provides a range of features and tools to enable developers to implement security features such as authentication, authorization, and attack prevention in their applications.

The Importance of Security in Applications

In today's world, security is a significant concern for software applications. Applications that lack proper security measures are vulnerable to various types of attacks, including data breaches, identity theft, and other malicious activities. Thus, it is essential for developers to implement robust security measures in their applications to prevent such attacks and safeguard sensitive data.

Spring Security Overview

Spring Security is an open-source security framework that provides a wide range of features to ensure the security of Java-based applications. It is built on the Spring Framework and is designed to be highly customizable and extensible. Spring Security offers a range of features, including authentication and authorization, secure session management, password management, and various attack prevention mechanisms.

Key Concepts of Spring Security

Spring Security provides several key concepts that are essential for understanding the framework's functionality. These concepts include:

  1. Authentication: Authentication is the process of verifying the identity of a user. Spring Security provides several authentication mechanisms, including form-based authentication, basic authentication, and OAuth2 authentication.
  2. Authorization: Authorization is the process of determining whether a user has access to a particular resource or functionality within an application. Spring Security provides several authorization mechanisms, including role-based access control, permission-based access control, and expression-based access control.

  3. Security Filters: Spring Security uses a chain of filters to process incoming requests and perform security-related actions such as authentication and authorization. These filters can be customized to suit specific application requirements.

  4. Security Context: The Security Context is a thread-local object that stores information about the currently authenticated user and their associated roles and permissions. The Security Context is used throughout the application to enforce security policies and restrictions.

  5. Access Control List (ACL): ACL is a mechanism for defining fine-grained access control rules for individual resources within an application. Spring Security provides support for ACLs through its integration with the Spring Framework's Security module.

  6. Password Encoding: Spring Security provides a range of password encoding mechanisms, including BCrypt, PBKDF2, and SHA-256. These mechanisms help to ensure that passwords are securely stored and transmitted.

  7. Cross-Site Request Forgery (CSRF) Protection: CSRF protection is a mechanism for preventing CSRF attacks, where an attacker tricks a user into performing an action on their behalf. Spring Security provides CSRF protection by generating and validating unique tokens for each user session.

Benefits of Spring Security

Some of the benefits of using Spring Security for security implementation in applications include:

  1. Customizability: Spring Security is highly customizable and extensible. It provides various configuration options that enable developers to implement security features that meet their application's specific requirements.

  2. Scalability: Spring Security is scalable and can be easily integrated into large enterprise applications.

  3. Integration with other Spring modules: Spring Security integrates seamlessly with other Spring modules, such as Spring Framework, Spring Data, and Spring MVC.

  4. Community Support: Spring Security has a large and active community that provides support, guidance, and updates.

Conclusion In conclusion, Spring Security is an essential tool for developers looking to implement security measures in their Java-based applications. Its comprehensive set of features, customizability, and community support make it an ideal choice for securing applications against various types of attacks. By implementing Spring Security, developers can ensure that their applications are secure, reliable, and trusted by their users.



Spring Security Implementation in spring boot


Implementing Spring Security in a Spring Boot application involves several steps. Here's a basic outline of the process:

  1. Add Spring Security to your dependencies: Open your pom.xml file and add the following dependency:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency>
  1. Create a Security Configuration class: Create a new class that extends the WebSecurityConfigurerAdapter class. This class is responsible for configuring Spring Security in your application.
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/dashboard") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } }
This configuration enables HTTP basic authentication for all requests except those that match /public/**, which are accessible without authentication. It also defines two users, "user" and "admin", with passwords "password" and roles "USER" and "ADMIN", respectively.
  1. Secure your endpoints: You can secure individual endpoints by adding the @Secured annotation to the method or class. For example:
@RestController public class MyController { @Secured("ROLE_USER") @GetMapping("/nik-endpoint") public String nikEndpoint() { return "Hello, user!"; } }
This endpoint can only be accessed by users with the "USER" role. You can add multiple role as well.
  1. Customize the login and logout pages: You can customize the login and logout pages by creating templates in your src/main/resources/templates directory. For example, create a file called login.html with the following contents:
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"/> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"/> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html>
  1. Test your application: Start your application and navigate to the login page. Enter the credentials of one of the users defined in your configuration, and you should be redirected to the dashboard page.

These are the basic steps for implementing Spring Security in a Spring Boot application. Of course, you can customize your configuration in many ways to fit your specific requirements.

Best Practices while implementing Spring security


Implementing Spring Security in Spring Boot is a critical aspect of building secure applications. Here are some best practices to follow while implementing Spring Security in Spring Boot:

  1. Use a Strong Password Encoder: Spring Security provides several password encoders such as BCrypt, SCrypt, and PBKDF2. It is essential to choose a strong password encoder to ensure the security of user passwords.

  2. Use HTTPS: It is recommended to use HTTPS to secure communications between the client and the server. Spring Boot makes it easy to configure HTTPS by using an SSL certificate.

  3. Implement Role-based Access Control (RBAC): Role-based access control allows you to restrict access to certain resources based on a user's role. It is essential to implement RBAC to prevent unauthorized access to sensitive information.

  4. Avoid Storing Sensitive Information in Plain Text: It is essential to avoid storing sensitive information such as passwords, API keys, and access tokens in plain text. Spring Security provides several ways to encrypt sensitive information, such as using Jasypt or the Spring Security Crypto module.

  5. Implement CSRF Protection: Cross-Site Request Forgery (CSRF) attacks are a common web application security vulnerability. Spring Security provides built-in CSRF protection, which you can enable by adding a CSRF token to each form.

  6. Keep Dependencies Up-to-date: It is crucial to keep your dependencies up-to-date to avoid security vulnerabilities. Spring Boot provides a dependency management plugin that makes it easy to manage your dependencies.

  7. Enable Security Auditing: Enabling security auditing can help you identify security vulnerabilities and track security-related events. Spring Security provides several auditing features, such as audit logging and event publication.

  8. Use Security Headers: Security headers can help protect your application against common web application security vulnerabilities such as cross-site scripting (XSS) and clickjacking. Spring Security provides built-in support for security headers, which you can configure in your application.

By following these best practices, you can improve the security of your Spring Boot applications and reduce the risk of security vulnerabilities.

Monday, 22 February 2016

How Heap is different from Stack memory

Major difference between Heap and Stack memory are as follows-

  1. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. 
  2. Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space. 
                       //Heap Memory allocation
                          A obj=new A();
                        //Stack Memory alllocation
                          int a;A obj;

     3. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. 

      4. When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space an error.

      5. We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.

To Understand Memory Managemet follow this link..
 
https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html#wp1085825

Thursday, 15 October 2015

Image Alignment along with Image Hyperlink URL in PDF using itextpdf

I am posting this simple but useful code for those friends who want's to align Image and also want to set anchor(for hyperlink) to that image. I found my team member struggling with Image alignment with it's hyperlink URL alignment  in a PDF file.

Jar Used - itextpdf.-5.4.3.jar

Code-

package com.nik.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfWriter;

public class FileGeneratorServiceImpl {
public static void main(String[] args) {
try {
createPdf("testPdf2.pdf");
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

protected static void createPdf(String filename) throws IOException,
DocumentException {
// ----------step 1-----------
Document document = new Document();
// ---------step 2------------
PdfWriter.getInstance(document, new FileOutputStream(filename));
// ---------step 3---------------
document.open();
// --------step 4---------------

Paragraph p = new Paragraph(200);

Image img = Image.getInstance("D:\\chrome.jpg");
img.setAlignment(Image.ALIGN_LEFT);
img.scaleAbsolute(100, 100);
Chunk imgChunk1 = new Chunk(img, 0f, -200f);
imgChunk1.setGenericTag("Google");
imgChunk1.setAction(new PdfAction(new URL("http://www.google.com")));
p = new Paragraph();
p.setAlignment(Paragraph.ALIGN_LEFT);
p.add(imgChunk1);

document.add(p);

// --------------------Adding 2nd Image in doc---------------

Image img2 = Image.getInstance("D:\\servicedesk.jpg");
img2.setAlignment(Image.ALIGN_RIGHT);
img2.scaleAbsolute(100, 100);
Chunk imgChunk2 = new Chunk(img2, 0f, -200f);
imgChunk2.setAction(new PdfAction(new URL("https://www.yahoo.com/")));
p = new Paragraph();
p.setAlignment(Paragraph.ALIGN_RIGHT);
p.add(imgChunk2);
document.add(p);

// step 5
document.close();// Closing the doc
}
}

Tuesday, 4 November 2014

JVM vs. JDK vs. JRE

JVM -
A Java virtual machine (JVM) is a virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform.JVM have different implementation based on operating systems( windows, linux , mac etc )
JDK -
The Java Development Kit (JDK) is an Oracle Corporation product aimed at Java developers. It is basically a super set  of JRE  which also include some tools like compilers, debugger etc.Since the introduction of Java, it has been by far the most widely used Java Software Development Kit (SDK).
JRE -
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

Wednesday, 22 October 2014

Java Composition Vs. Inheritance

What is Java Composition?

Java composition is a design technique using which we can reuse the java code.This is applicable when there is a has a relationship between two entity or classes.

eg. Student has an Address

Student.java
package com.nik.composition;
public class Student{

public void displayDetail(){
System.out.println("Student Detail is aaaa");
}
}


Address.java
package com.nik.composition;
public class Address{
Student stud; // Create Student instance variable as a data member of the Adderss class

public Address(){
stud=new Student();    //Initialize Student Object along with Address object
}
public void displayAddress()
{
System.out.println("Student Address is xxx");
}

public displayStudentCompleteDetail(){   // new method to access the Student method
stud.displayDetail();
 System.out.println("Student Address is xxx");
}
}

MainClass.java
public class MainClass{
public static void main(String[] arg) {
   Address addr=new Address();
   addr.displayStudentCompleteDetail(); // No need to create Student object
}
}

Advantage of using Java composition over Inheritance

1)Your code becomes loosely coupled and more flexible if you use composition.Changes in superclass  methods has no effect in their child classes overridden methods.
2)This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model
3)Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance.


Friday, 25 April 2014

How to schedule a task in java

Here is an easy code to explain the TimerTask ...

Create a TimerTask by creating a class which will extend TimerTask..
The code is  given below

package com.nik.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    int time;

    public void myTask() {
        System.out.println("This task is invoked after " + time + " minute");
    }

    public MyTimerTask(int time) {
        this.time = time;
    }

    @Override
    public void run() {
        myTask();
    }

}


 Another class to invoke the timer

 package com.nik.timer;

import java.util.Timer;

public class TimerDemo {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Timer started........");
        Timer myTimer = new Timer();
        myTimer.schedule(new MyTimerTask(1), 6000);
        Thread.sleep(6000);
        myTimer.cancel();
    }

}

Saturday, 7 December 2013

Get All System Properties

Simple but useful  ......


package com.nik;

import java.util.Iterator;
import java.util.Properties;


//Reference of Doc  http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

//"file.separator"     Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
//"java.class.path"     Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
//"java.home"     Installation directory for Java Runtime Environment (JRE)
//"java.vendor"     JRE vendor name
//"java.vendor.url"     JRE vendor URL
//"java.version"     JRE version number
//"line.separator"     Sequence used by operating system to separate lines in text files
//"os.arch"     Operating system architecture
//"os.name"     Operating system name
//"os.version"     Operating system version
//"path.separator"     Path separator character used in java.class.path
//"user.dir"     User working directory
//"user.home"     User home directory
//"user.name"     User account name

public class ReadSystemProperties {
    public static void main(String arg[]){
        Properties properties=System.getProperties();
        Iterator<Object> sysProp=properties.keySet().iterator();
       
        while(sysProp.hasNext())
            System.out.println(sysProp.next().toString()+" --> "+properties.get(sysProp.next().toString()));
       
    }

}

Thursday, 7 November 2013

Convert Html To PDF for Simple and Special Char Using Java

Convert Html To PDF

import com.nik.pdf;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.clapper.util.html.HTMLUtil;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class HtmlToPdf {

    public static void convertHtmlToPdf() {

        try {

            StringBuffer bufferForHtml = new StringBuffer();
            bufferForHtml
                    .append("<html>"
                            + "<head>"
                            + "<style language='text/css'>"
                            + ".c1{font-size:12px;font-family:\"Times New Roman\";}"
                            + ".pos_right{position:relative;left:20px;}"
                            + ".pos_top{position:relative;top:-50px;}"
                            + ".top_alignment{vertical-align:text-top;}"
                            + ".bottom_alignment{vertical-align:text-bottom;}"
                            + "table.layout1 {table-layout:auto;}"
                            + "table.layout2 {table-layout:fixed;}"
                            + "</style>"
                            + "</head>"
                            + "<body class='c1'>"
                            + "<p align=\"center\">This is a test PDF  by Nitesh  &copy;</p>"
                            + "<p>Few mathematical notations : &#8825;&#8904;&#8939; </p>"
                            + "</body></html>");
            String htmlConvert = HTMLUtil
                    .convertCharacterEntities(bufferForHtml.toString());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(
                    htmlConvert.getBytes("UTF-8")));
            ITextRenderer renderer = new ITextRenderer();
//For mathematical latin symbols use -->renderer.getFontResolver().addFont("E:\\ARIALUNI.TTF",BaseFont.IDENTITY_H, //BaseFont.NOT_EMBEDDED);
//Change  BaseFont for different type of Character encoding like BaseFont.CP152 for chinese char
            renderer.setDocument(doc, null);
            OutputStream outputFile = new FileOutputStream("E:\\test.pdf");
            renderer.layout();
            renderer.createPDF(outputFile);
            outputFile.close();
        }

        catch (Exception e) {
            System.out.println("catch me");
            throw new RuntimeException(e);

        }

    }

    public static void main(String[] arg) {
        convertHtmlToPdf();
    }

}

Friday, 19 July 2013

This code will help u to authenticate your web application using system credential

Java  Network HTTP Authentication :-


This code will help u to authenticate your web application using system credential.


If u want to set the authentication for network http authentication for your application U need to override the method of Authenticator Class and set your password
 static class CustomAuthenticator extends Authenticator {
   static final String userId="test";
static final String password="password";
        public PasswordAuthentication getPasswordAuthentication() {
                                  return (new PasswordAuthentication(userId,password.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new CustomAuthenticator ());//set the custom default network login password
        PasswordAuthentication pswAuth=new CustomAuthenticator().getPasswordAuthentication();
        System.out.println("Default authentication User :"+pswAuth.getUserName());
        System.out.println("Default authentication Password :"+pswAuth.getPassword().toString());           }
}


Saturday, 4 May 2013

String argument in switch statement.. JDK 7 useful feature

String argument in switch statement
In the JDK 7 release, we can use a String object in the expression of a switch statement..
Example given below

class TestClass{
public integer getIntegerFromString(String stringFormat) {
     integer number;
     switch (stringFormat) {
         case "One":
            number=1;
             break;
         case "Two":number=2;break;
         case "Three":number=3;break;
         case "Four":number=4;break;
            
         case "Five": number=5;
             break;
         case "Six":number=6;break;
         case "Seven":
            number=7;break;
         case "Eight":
             number=8;break;
         case "Nine":
            number=9;break;
         case "Zero":
            number=0;break; 
   default:System.out.println("Not an integer value");
            
     }
     return number;
}
 
public static void main(String arg[])
{
          TestClass obj=new TestClass();
          System.out.println("Integer value of Three is "+obj.getIntegerFromString("Three") ;
 
} 
 
 
} 


The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements