org.soulwing.credo.service.crypto.ConcretePasswordGenerator.java Source code

Java tutorial

Introduction

Here is the source code for org.soulwing.credo.service.crypto.ConcretePasswordGenerator.java

Source

/*
 * File created on Mar 12, 2014 
 *
 * Copyright (c) 2014 Virginia Polytechnic Institute and State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.soulwing.credo.service.crypto;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

import org.apache.commons.codec.binary.Base64;
import org.soulwing.credo.Password;

/**
 * A concrete {@link PasswordGenerator} implementation.  This implementation
 * produces a password by generating a sequence of random bytes and then
 * applying a base 64 encoding to the generated bytes to produce the password
 * text.
 *
 * @author Carl Harris
 */
@ApplicationScoped
public class ConcretePasswordGenerator implements PasswordGenerator {

    static final int RAW_LENGTH = 24;

    private SecureRandom secureRandom;

    /**
     * Initializes the receiver.
     */
    @PostConstruct
    public void init() {
        try {
            secureRandom = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Password generatePassword() {
        byte[] data = new byte[RAW_LENGTH];
        secureRandom.nextBytes(data);
        byte[] encoded = Base64.encodeBase64(data);
        try {
            Reader reader = new InputStreamReader(new ByteArrayInputStream(encoded), "US-ASCII");
            char[] password = new char[RAW_LENGTH * 4 / 3];
            int i = 0;
            while (i < password.length) {
                password[i++] = (char) reader.read();
            }
            return new Password(password);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

}