demo.learn.shiro.tool.PasswordEncryptionTool.java Source code

Java tutorial

Introduction

Here is the source code for demo.learn.shiro.tool.PasswordEncryptionTool.java

Source

/**
 * Copyright 2013 Jee Vang
    
   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 demo.learn.shiro.tool;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.util.ByteSource;

import demo.learn.shiro.constant.S;

/**
 * Password encryption tool.
 * @author Jee Vang
 *
 */
public class PasswordEncryptionTool {

    /**
     * Main method.
     * @param args Requires a plain text password.
     */
    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        String plainTextPassword = "root";

        Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
                .isRequired(false).create('p');

        Options options = new Options();
        options.addOption(p);

        try {
            CommandLineParser parser = new BasicParser();
            CommandLine cmd = parser.parse(options, args);

            if (cmd.hasOption("p")) {
                plainTextPassword = cmd.getOptionValue("p");
            }
        } catch (ParseException pe) {
            String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordEncryptionTool";
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(cmdLineSyntax, options, false);
            return;
        }

        final RandomNumberGenerator rng = new SecureRandomNumberGenerator();

        final ByteSource salt = rng.nextBytes();
        final String saltBase64 = Base64.encodeToString(salt.getBytes());
        final String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, S.HASH_ITER).toBase64();

        System.out.print("-p " + plainTextPassword);
        System.out.print(" -h " + hashedPasswordBase64);
        System.out.println(" -s " + saltBase64);
    }

}