Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Tuesday, 2 April 2013

Creating A Customized Spring User & Persistence

This post explains how to create a customized Spring user and persistence mechanism for authentication. The code is available at GitHub in the Spring-MVC-Customized-User directory.

Things To Take Into Consideration

Before creating a customized user, we need to remind what a user is in Spring. We know from here that a user is an implementation of the UserDetails interface. Spring security also requires a loading mechanism, as an implementation of the UserDetailsService interface. To keep this example simple, we are not going to implement login/logout or other security features.

The UserDetails interface is a bit incomplete in order to define a user in a real application. It defines getters and no setters. It is not a big deal, but the real pain is that the username (a string) is considered as 'the' key. Most software developers will prefer a long id.

To solve these issues, we define a PracticalUser interface:
public interface PracticalUserDetails
        extends UserDetails, CredentialsContainer {

    long getId();

    void setPassword(String password);

    void setAccountExpired(boolean b);

    void setAccountLocked(boolean b);

    void setCredentialsExpired(boolean b);

    void setEnabled(boolean b);

    void setAuthorities(
        Collection<? extends GrantedAuthority> authorities);

}
Typically, one would use JPA annotations on the implementation bean and save it in a database in a real application. However, for this example, the DAO will register users in an in-memory map as described further.

The UserDetailsService interface does not provide a get user per name or id, which is necessary for an administrator (for example). More, it does not allow to retrieve all existing users' id and name, or to update or insert users, or even to delete them.

Therefore, we create a PracticalUserDetailsService interface to solve these issues:
public interface PracticalUserDetailsService
        extends UserDetailsService {

    Set<PracticalUserDetailsDAO.UserIdentifiers> getUsers();

    void deleteUser(long id);

    void upsertUser(PracticalUserDetails user);

    PracticalUserDetails getUser(long id);

    PracticalUserDetails getUser(String username);

}
The corresponding implementation is called PracticalUserDetailsServiceInMemory for this example.

In-Memory DAO

To keep this example simple, we define a simple PracticalUserDetailsDAO:
public interface PracticalUserDetailsDAO<U extends PracticalUserDetails> {

    void create(U user);

    boolean contains(U user);

    U read(String username);

    U read(long id);

    void update(U user);

    void delete(String username);

    void delete(long id);

    interface UserIdentifiers {
        long getId();
        String getUsername();
    }

    Set<UserIdentifiers> getUsers();

}
We also define a special user id and name identifier interface to retrieve the set of existing user data, without returning all users. Our implementation of PracticalUserDetailsDAO is PracticalUserDetailsDAOInMemory.

In a real implementation, using a JPA Repository is more appropriate.

Configuration

In the security.xml file, we define our practical user detail service (it will be registered in the authentication manager) and the in-memory DAO bean:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http auto-config="true">
    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref='practicalUserDetailsServiceInMemory' />
    </authentication-manager>

    <beans:bean id="pud"
        class="com.jverstry.DAO.PracticalUserDetailsDAOInMemory">
    </beans:bean>

</beans:beans>

The JSP Pages

We use two pages. The main page displays registered users (together with a delete link) and registration form:


The second page is displayed when the Create User button is clicked to check the name and the password:


The Controller

The controller is used to check the username and password:
@Controller
public class MyController {

    @Autowired
    private PracticalUserDetailsServiceInMemory pudm;

    @RequestMapping(value = "/")
    public ModelAndView index() {

        ModelAndView result = new ModelAndView("index");

        result.addObject("users", this.pudm.getUsers());

        return result;

    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable(value="id") String id) {

        this.pudm.deleteUser(Long.parseLong(id));

        return "redirect:/";

    }

    @RequestMapping(value = "/create")
    @SuppressWarnings("AssignmentToMethodParameter")
    public ModelAndView add(
            @RequestParam(value="name")
            String name,
            @RequestParam(value="password")
            String password) {

        name = StringUtils.replace(name, " ", "");
        password = StringUtils.replace(password, " ", "");

        String errorMsg = "";

        if ( name.length() == 0 ) {
            errorMsg += "Name is empty ";
        }

        if ( password.length() == 0 ) {
            errorMsg += "Password is empty ";
        }

        if ( errorMsg.isEmpty() ) {
            this.pudm.upsertUser(new PracticalUserDetailsImpl(name, password));
        }

        ModelAndView result = new ModelAndView("create");

        result.addObject("errorMsg", errorMsg);
        result.addObject("username", name);

        return result;

    }

}

Running The Example

One can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:9191/spring-mvc-customized-user/

More Spring related posts here.

Execute Spring ACL SQL Script In Memory

This post describes how to execute the Spring ACL script to create ACL tables in an in-memory HSQL database instance. The code is available at GitHub in the Execute-ACL-SQL-Scripts-In-Memory directory.

In-Memory DataSource

We are using a configuration classe implementing the DisposableBean interface to shut down the created HSQL embedded database nicely.
@Configuration
public class InMemoryDataSource implements DisposableBean {

    private EmbeddedDatabase ed;

    @Bean(name="hsqlInMemory")
    public EmbeddedDatabase hsqlInMemory() {

        if ( this.ed == null ) {

            EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();

            this.ed = builder.setType(EmbeddedDatabaseType.HSQL)
                .addScript("aclSchema.sql").build();

        }

        return this.ed;

    }

    @Override
    public void destroy() {

        if ( this.ed != null ) {
            this.ed.shutdown();
        }

    }

}
When creating the database, we also have the aclSchema.sql script executed. It must be located at the root of the resource directory:


The content of the script is taken from the Spring documentation appendix.

Checking Table Creation

We extract the list table of tables in the controller. Technically speaking, we should do this at the service/DAO level, but for the sake of this example, we'll keep it simple:
@Controller
public class MyController {

    @Autowired
    EmbeddedDatabase hsqlInMemory;

    @RequestMapping(value = "/")
    public ModelAndView home() {

        ModelAndView result = new ModelAndView("index");

        ArrayList<String> tables = new ArrayList<String>();

        JdbcTemplate tplate = new JdbcTemplate(hsqlInMemory);

        SqlRowSet retr = tplate.queryForRowSet(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");

        while (retr.next()) {
            tables.add(retr.getString(1));
        }

        result.addObject("tables", tables);

        return result;

    }

}

Running The Example

One can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:8585/execute-acl-sql-scripts-in-memory/

We find the tables we have created:


More Spring related posts here.

Monday, 11 February 2013

Securing A Service And JSP Pages

Securing A Spring Service

When a service is implemented in Spring, it can be secured with the @Secured annotation. It has a parameter where the list of roles can be defined. In order to enable this annotation, one must add the the following line in the Spring Security configuration XML file:

  <security:global-method-security secured-annotations="enabled"/>

A complete example is available here.

Securing A JSP Page

Spring defines its own set of JSP tags to control what is displayed to users. This is achieved with the Authorization tag. The Authentication tag can be used to retrieve user details data too.

Sunday, 11 November 2012

The Authenticated User Concept In Spring Security

A user, in the Spring Security context, is an instance of a class implementing the UserDetails interface. One can use it to check whether:
  • the user account is expired or locked
  • the user is enabled or not
  • credentials are expired or not
As a reminder, authentication requests are managed by an authentication manager delegating these to authentication providers. The laters can be used to authenticate authentication requests.

By default, Spring configures a DaoAuthenticationProvider instance, and registers it in the default authentication manager. The main purpose of this provider is to let software developers choose the way they want to store UserDetails by setting an object implementing UserDetailsService. Such services have one function: load a user's details from its name. That's it! It can be a database, an in-memory database, etc...

If you want to implement your own UserDetailsService, Marc Serrano has provided a detailed example using a JPA Repository which eliminates a lot of the boiler-plate code. Such repositories are part of the Spring JPA Data features.

To implement a customized user and corresponding persistence, see the example available here.

More Spring related posts here.

Thursday, 27 September 2012

Spring MVC Customized User Login Logout Implementation Example

This post describes how to  implement a customized user access to an Spring MVC web application (login logout). As a prerequisite, readers are advised to read this post which introduces several Spring Security concepts.

The code example is available from Github in the Spring-MVC-Login-Logout directory. It is derived from the Spring MVC with annotations example.

Customized Authentication Provider

In order to implement our own way of accepting user login requests, we need to implement an authentication provider. The following lets users in if their id is identical to their passwords:
public class MyAuthenticationProvider implements AuthenticationProvider {

    private static final List<GrantedAuthority> AUTHORITIES
        = new ArrayList<GrantedAuthority>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
    }

    @Override
    public Authentication authenticate(Authentication auth)
        throws AuthenticationException {

        if (auth.getName().equals(auth.getCredentials())) {
            return new UsernamePasswordAuthenticationToken(auth.getName(),
                auth.getCredentials(), AUTHORITIES);
        }

        throw new BadCredentialsException("Bad Credentials");

    }

    @Override
    public boolean supports(Class<?> authentication) {
        
        if ( authentication == null ) return false;

        return Authentication.class.isAssignableFrom(authentication);
    }

}

Security.xml

We need to create a security.xml file:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http>
        <intercept-url pattern="/*" access="ROLE_ANONYMOUS"/>
        <form-login
            default-target-url="/"
            always-use-default-target="true" />
        <anonymous />
        <logout />
    </http>

    <authentication-manager alias="authenticationManager">
      <authentication-provider ref="myAuthenticationProvider" />
    </authentication-manager>

    <beans:bean id="myAuthenticationProvider"
      class="com.jverstry.LoginLogout.Authentication.MyAuthenticationProvider" />
    </beans:beans>
The above makes sure all users have the anonymous role to access any page. Once logged in, they are redirected to the main page. If they don't log in, they are automatically considered as anonymous users. A logout function is also declared. Rather than re-implementing the wheel, we use items delivered by Spring itself.

Main Page

We implement a main page displaying the name of the currently logged in user, together with login and logout links:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome To MVC Customized Login Logout!!!</title>
</head>
  <body>
    <h1>Spring MVC Customized Login Logout !!!</h1>
    Who is currently logged in? <c:out value="${CurrPrincipal}" /> !<br />
    <a href="<c:url value='/spring_security_login'/>">Login</a>&nbsp;
    <a href="<c:url value='/j_spring_security_logout'/>">Logout</a>
  </body>
</html>

Controller

We need to provide the currently logged in user name to the view:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("CurrPrincipal",
            SecurityContextHolder.getContext()
                .getAuthentication().getName());

        return "index";

    }

}

Running The Example

Once compiled, one can start the example by browsing: http://localhost:9292/spring-mvc-login-logout/. It will display the following:

Srping Customized Login Logout

Log in using the same id and password:


The application returns to the main and displays:




More Spring related posts here.

Monday, 17 September 2012

Spring Security And Annotation Configuration Example

This post is the mix between the Spring MVC with Annotations Example and the Spring Security Configuration Introduction. The code example is available on Github in the Spring-Security-And-Annotation-Config directory.

We are going to add a mandatory login page before one can access the main page of the Spring MVC with Annotations example.

Configuration

First, we create a MyServlet-security.xml file:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/security

    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <http auto-config="true">
    <intercept-url pattern="/*" access="ROLE_USER"/>
  </http>

  <authentication-manager alias="authenticationManager">
    <authentication-provider>
      <user-service>
        <user authorities="ROLE_USER" name="guest" password="guest"/>
      </user-service>
    </authentication-provider>
  </authentication-manager>

</beans:beans>
We rely on the automatic configuration of Spring security, and we request that one must login with ROLE_USER privilege to access any to page of the website. We set an authentication manager and create a simple guest user login, with the guest password.

We add the security filters under contextConfigLocation:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      com.jverstry.Configuration
    </param-value>
  </context-param>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
      org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file></welcome-file>
  </welcome-file-list>

</web-app>
At last we add one @ImportSource line in our WebConfig configuration class:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
@ImportResource("/WEB-INF/MyServlet-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {

  @Bean
  public ViewResolver getViewResolver() {

    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("WEB-INF/pages/");
    resolver.setSuffix(".jsp");

    return resolver;

  }

}

Running The Example

After compiling the project, one can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:9191/spring-mvc-with-annotations/

Login with guest guest:


 ...and access the main page:


More Spring related posts here.

Saturday, 15 September 2012

Spring Security Configuration Introduction

This post describes the basic Spring security configuration steps all Spring applications must implement.

Setting Filters

Spring security relies on user request filters. These must be configured in the web.xml file under the contextConfigLocation elements:
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Security Configuration

A <name>-security.xml file must be created in /WEB-INF with this initial structure:
<beans:beans
  xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    ...
</beans:beans>
<name> must be the name of the servlet as configured in web.xml.

Spring configuration can only be performed with XML documents. However, one can mix Java configuration and Spring XML configuration like this when using MVC:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "my.packages")
@ImportResource("WEB-INF/<name>-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}
The above imports the Spring security configuration.

REM: the tutorial available here recommends configuring the <name>-security.xml file in the contextConfigLocation section of web.xml. However, it does not work when using Java configuration. One must use @ImportResource as described above.

Maven Dependencies

The following maven dependencies are required for Spring security:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
...
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

For a concrete Spring Security example, click here • More Spring related posts here.

Friday, 31 August 2012

Introduction to Spring Security Concepts

Spring security is a complex subject, with a steep learning curve. The purpose of this post is to try to reduce that learning curve and to be a reminder of the main security concepts every developers should master in order to configure security in Spring applications.

It is a not a substitute to reading the official documentation, especially the Spring security appendix describing the nuts and bolts of configuration elements. The Spring security 3 book is also helping connecting dots between concepts.

Facts

  • Authentication and Access Authorization – The main philosophy of Spring security is first to authenticate users, then to check their access credentials to resources. This is performed via a set of filters.
  • Annotation based configuration – So far, there is no such thing as Java based configuration with Spring security. Everything is based on XML configuration. You will not get rid of security.xml with Java programmatic configuration.
  • <servlet-name>-security.xml – One must specify the location of the security configuration XML file either in the contextConfigLocation parameter value (*) of web.xml or, if one uses configuration annotations, it can be imported with @ImportResource (**).
  • web.xml – One must configure the Spring security filter chain in the web.xml file (***) together with a filter mapping configuration to enable the Spring security.
  • Security Annotations - It is possible to enable JSR-250 annotations or Spring's @Secured annotations. Typically, these are used on services objects for access control.

Concepts

  • Auto-Config – A configuration element of the Spring Security namespace enabling (or not) the default configuration of Spring Security.
  • Access Decision Manager – Decides whether a user can access a resource or not.
  • Authentication Manager – It processes authentication requests via child authentication providers.
  • Authentication Provider – Depending on its accepted types of authentication requests, it processes them for approval or not.
  • Delegating Filter Proxy – A servlet filter capturing every user requests and sending them to the configured security filters to make sure access is authorized.
  • Principal – Represents anyone authenticated.
  • Provider Manager – An authentication manager instance processing authentication request through a list of authentication providers.
  • Security Context – A user's secured authenticated session. It is stored in a security context repository.
  • Session Authentication Strategy – Should a user have a session? Should we retrieve any existing ones? Should we automatically create one at each login? How many sessions can a user have? What about timeout? What's the strategy for session handling?

General Scheme

For a secured page, the general functional behavior of Spring security is the following:
  1. A user makes a request for a secured page.
  2. The configured Authentication Manager checks the user credentials.
  3. If necessary, the user provides them (for example, login and password).
  4. If the credentials are not validated successfully, access to the page is refused.
  5. The configured Access Decision Manager then makes sure the identified user has the right to access the page (i.e. has proper authority).
  6. If the authority is not established, access to the page is refused.
  7. Else, the page is displayed.

Security Filters

Every user requests pass through a set of filters. The Authentication Manager and the Access Decision Manager are both filters, functionally speaking. When auto-config is enabled, a set of defaut Spring security filters is automatically configured.

Here is how user queries are processed in more details:
  1. When a user makes a request, Spring loads its security context.
  2. If the user's request URL is the logout URL (by default /j_spring_security_logout), the user is logged out.
  3. If the user's request URL is an authentication form submission (by default  /j_spring_security_check), an attempt to authenticate the user is performed.
  4. If no login page is configured, a default login page is displayed (if the user is not authenticated yet).
  5. Checks whether the request has an Authorization header. If yes, user name and password is extracted for authentication. If authentication is successful, it is registered in the security context.
  6. Assuming a user was trying to access a page requiring authentication, this step retrieves the original request to that page, if the authentication is successful.
  7. The user request is wrapped together with the security context into a single object.
  8. If the user has not been authenticated successfully so far, it is flagged as anonymous.
  9. If the user has been authenticated, the session authentication strategy is applied. 
  10. Any AccessDeniedException and AuthenticationException thrown by any of the above are handled here.
  11. Delegation of authorization and access control decisions to an access decision manager.

Security Namespace

Spring security is defined in an XML document, just like maven configuration is defined in a pom.xml file. It has a namespace (i.e., a set of XML tag elements) which can be used to activate or configure Spring security features. Again, read the Spring security appendix to learn about these in details. It is a must to understand Spring Security.

Some of its main elements are:
  • <html auto-config='true'> - It is the parent element of web related configuration elements. It creates the filter chain proxy bean called springSecurityFilterChain for security. It has an auto-config attribute, which can be set to install the default Spring security configuration elements.
  • <access-denied-handler> - Can be used to set the default error page for access denials.
  • <intercept-url pattern="/**" access="ROLE_USER"> - This element creates a relationship between a set of URLs and the required access role to visit these pages.
  • requires-channel - This is an <intercept-url> attribute which can be used to require the usage of https to access a set of URLs (i.e., secured channels).
  • <form-login> - Can be used to define the login page URL, the URL for login processing, the target URL after login, the login failure URL, etc...
  • <remember-me> - If a user is not authenticated, and 'remembered' information about the user is available (for example, from a cookie), it will be used.
  • <session-management> and <concurrency-control> - To implement session management strategies.
  • <logout> - To configure the default logout page.
  • <http-firewall> - To implement a firewall filter.
  • <authentication-manager> - A required configuration element. It creates a provider manager. The child elements are <authentication-provider>.
  • <authentication-provider> - Can be used to create an in-memory authentication provider. The children <user-service> and <user> elements can be used to define user login-password combinations. Other types of authentication providers can be configured too.
  • <password-encoder> - If the users' login and password are stored in a database (for example), one can use this configuration element to specify how the password should be encrypted.

For a concrete Spring Security example, click here • More Spring related posts here.

REM: This blog does not cover all Spring Security features. Topics such as: password encryption, storage of credentials, 'Remember Me', SSL connections, sophisticated access control, OpenID, LDAP, Client Certificate Authentication in the Spring Security 3 book in details.

------------------------------------------------------------

(*)
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/myApp-security.xml
  </param-value>
</context-param>

(**)
@Configuration
@ImportResource("classpath:my/package/security.xml")
public class ApplicationConfig {

    // ...

}
(***)
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Saturday, 18 August 2012

Generate A Random Number Within a Range in Java

Java provides two classes to generate random numbers: Random and SecureRandom. Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type. Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double (inclusive means the max value is included for int and long):
int min = 122;
int max = 134;

SecureRandom rnd = new SecureRandom();
int inclusive = max - min + 1;
int exclusive = max - min;

int rndIntIncl = rnd.nextInt(inclusive) + min;
int rndIntExcl = rnd.nextInt(exclusive) + min;

System.out.println("Integer (incl.): " + rndIntIncl);
System.out.println("Integer (excl.): " + rndIntExcl);

long rndLongIncl = ( Math.abs(rnd.nextLong()) % inclusive ) + min;
long rndLongExcl = ( Math.abs(rnd.nextLong()) % exclusive ) + min;
System.out.println("Long    (incl.): " + rndLongIncl);
System.out.println("Long    (excl.): " + rndLongExcl);

float rndFloat = ( rnd.nextFloat() * exclusive ) + min;
System.out.println("Float          : " + rndFloat);

double rndDouble = ( rnd.nextDouble() * exclusive ) + min;
System.out.println("Double         : " + rndDouble);
The above generates something similar to this:
Integer (incl.): 129
Integer (excl.): 130
Long    (incl.): 125
Long    (excl.): 127
Float          : 125.42884
Double         : 127.84922531497857

Tuesday, 14 August 2012

How to Generate Diffie-Hellman or DSA Parameters?

Java provides a cryptography algorithm parameter generator for the Diffie-Hellman protocol and DSA (Digital Signature Algorithm).

For the Diffie-Hellman protocol:
AlgorithmParameterGenerator apg
    = AlgorithmParameterGenerator.getInstance("DiffieHellman");
apg.init(512);

AlgorithmParameters ap = apg.generateParameters();
DHParameterSpec dps = (DHParameterSpec)
    ap.getParameterSpec(DHParameterSpec.class);

System.out.println("Diffie-Hellman");
System.out.println("L :" + dps.getL());
System.out.println("P :" + dps.getP());
System.out.println("G :" + dps.getG());
The generated output is:
Diffie-Hellman
L :511
P :8266077972939539471508511844788321242135959675971529125376989640166743180991072673735061975276152293501435845844404151584495666060797732285698897055150387
G :2019537923026914368988722563706571073299959195070870668709287200992494530060354049564673739869083497959173115010462554070989621918531942099145869042943787
For the DSA:
AlgorithmParameterGenerator apg
    = AlgorithmParameterGenerator.getInstance("DSA");
apg.init(512);

AlgorithmParameters ap = apg.generateParameters();
DSAParameterSpec dps = (DSAParameterSpec)
    ap.getParameterSpec(DSAParameterSpec.class);

System.out.println("DSA");
System.out.println("P :" + dps.getP());
System.out.println("Q :" + dps.getQ());
System.out.println("G :" + dps.getG());
The generated output is:
DSA
P :8197719696944927589177120726843658828192492967000538281179885268382184665678774153545503826581953282213697665107441101650781498069116236522448234275281441
Q :1284267634964328541131115801052780210043074500583
G :570004927801867375990232729480351281559717810987031405643673487612900545268295697120844288618676632560887588778557548200272181177045246836759460884667572

Monday, 13 August 2012

How to Generate a Public Private Key Pair in Java?

Java offers features to generate public/private key pairs. The list of available algorithms is: DiffieHellman (Diffie-Hellman), DSA (Digital Signature Algorithm), RSA (Rivest, Shamir and Adleman, and EC (Elliptic Curve).
public static KeyPair generateKeyPair(String algorithm, int keysize)
       throws NoSuchAlgorithmException {

   KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
   keyGen.initialize(keysize);

   return keyGen.genKeyPair();

}
Considering the above method and the following:
KeyPair kp = generateKeyPair("RSA", 1200);

System.out.println(kp.getPublic());
System.out.println(kp.getPrivate());
The generated output is:
Sun RSA public key, 1200 bits
  modulus:          9869434664406071422397837320764405182639187275838230993850845712119792960719253107137826291378531088798687188823076370201242339197879199249064933049166569948405393151733986369838996220598856887300012669754735304190978435430220593101694644244314877878605534096811338814490286832890418449631509846730240623970004851838612509884903198786095740146540225924110683179
public exponent: 65537
Sun RSA private CRT key, 1200 bits
  modulus:          9869434664406071422397837320764405182639187275838230993850845712119792960719253107137826291378531088798687188823076370201242339197879199249064933049166569948405393151733986369838996220598856887300012669754735304190978435430220593101694644244314877878605534096811338814490286832890418449631509846730240623970004851838612509884903198786095740146540225924110683179
  public exponent:  65537
  private exponent: 1582133460247649211341863052809113033077609617772501866447914690198369544613218077476692601388877239100340381857198839515605719145107631831037065880564322197811115254773902693158497157951570638902393594757932655753965475860517442661157051743687056572748027450726509909507973409417657097270834672334740647227515714009141606345006585607294455971993731635917157153
  prime p:          3256149439130022408436310311885111793464195858196258233187003768668905068326967709908800218408588778082838728236339782637613895789098072922267211467323843674447148299706221862611571
  prime q:          3031014039405693160199592278696049712727614456472639744562120993703109441692657536297714688397058789187582744250860764288923138208010664879900484905834875292341824001685681393062249
  prime exponent p: 651011277612961893552359339253103129983999242106681288881842476476931551799567540518104418295127008548139766179116532216925627912851550261691369331161699859106779135008478036312303
  prime exponent q: 2314803602335998723791900653692051576540424968504998578742980573658152351590081974292947767962543135291937438889479715480185116658515674930251600928055012332834896823296306504785977
  crt coefficient:  1264506160423420660013941104026558245174285118352499963549245021823942032361239666081851546710377637751263799087922801195636712628068424427135886836129544889379051273632748195244747

Saturday, 28 July 2012

About Using System.Exit() in Try Catch Finally Java Statements

This post is an attempt at summarizing issues around using the Java system.exit() statements inside try {...} catch (...) {...} finally {...} statements.

We will use the following piece of code:
public class TryCatchFinallySystemExit {

  public static void main(String[] args) {

    System.setSecurityManager(new SecurityManager() {

      @Override
      public void checkPermission(Permission perm) { }

      @Override
      public void checkExit(int status) {
        // throw new SecurityException();
      }

    });

    System.out.println("Before Check");
    check();
    System.out.println("After Check");

  }

  public static void check() {

    try {

      System.out.println("Before System.exit(-1)");
      System.exit(-1);
      System.out.println("After System.exit(-1)");

    } catch(Throwable t) {

      System.out.println("Before System.exit(-2)");
      System.exit(-2);
      System.out.println("After System.exit(-2)");

    } finally {

      System.out.println("Before System.exit(-3)");
      System.exit(-3);
      System.out.println("After System.exit(-3)");

    }

    System.out.println("After try statement");

  }

}

The main method implements a SecurityManager, then calls the check() method. If we run this application as is, the output is the following:

Before Check
Before System.exit(-1)

We can conclude that:
  • System.exit(-1) is the last statement excuted.
  • Catch and Finally statements are not called.
  • The check() method does not return.

If we uncomment the throw new SecurityException(); and execute the application again, we get:

Before Check
Before System.exit(-1)
Before System.exit(-2)
Before System.exit(-3)

We can conclude that:
  • The SecurityException get the catch and finally statements to be executed.
  • Statements after System.exit() statements are not executed.
  • The check() method does not return.

For return, continue and break statements in try statements, see this post.

Disclaimer: this post contains information from personal notes and information available on StackOverflow.com.