JavaWeb日記——Shiroのパスワード暗号化

21072 ワード

一般的にパスワードをデータベースに保存するのは暗号化方式で、データベースが漏れても不法分子がアカウントにログインできないことを確保しています.一般的な暗号化アルゴリズムとしてはMD 5,SHA 1などがありますが、このブログではShiroでMD 5アルゴリズムを使って暗号化する方法について説明します.
POM

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.jk.shiroLearninggroupId>
    <artifactId>chapter4artifactId>
    <version>1.0-SNAPSHOTversion>
    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.9version>
        dependency>
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.1.3version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-coreartifactId>
            <version>1.2.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.25version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>0.2.23version>
        dependency>
    dependencies>

project>

shiro-realm.ini
[main]
#   authorizer
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer

#   realm      securityManager.authorizer    (    setRealms  realms   authorizer,    Realm  permissionResolver rolePermissionResolver)
realm=com.jk.realm.MyRealm
#       
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#    
credentialsMatcher.hashAlgorithmName=MD5
#    
credentialsMatcher.hashIterations=1024
realm.credentialsMatcher=$credentialsMatcher

securityManager.realms=$realm

以前よりも多くの暗号化マッチングを構成する部分
カスタムRealm
public class MyRealm extends AuthorizingRealm {

    //  ,  checkRole/checkPermission/hasRole/isPermitted       
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //     principal      
        if (principals.getPrimaryPrincipal().equals("jack")){
            //    role1
            authorizationInfo.addRole("role1");
            authorizationInfo.addRole("role2");
            //   user           
            authorizationInfo.addObjectPermission(new WildcardPermission("user:*"));
            //   
            //authorizationInfo.addStringPermission("user:*");
        }
        return authorizationInfo;
    }

    //  
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();  //     
        //    
        String hashAlgorithName="MD5";
        //    
        String credentials="123456";
        //    
        ByteSource salt = null;
        //    
        //        ,           
        //ByteSource salt= ByteSource.Util.bytes(username);
        //    
        int hashIterations = 1024;
        Object password = new SimpleHash(hashAlgorithName,credentials,salt,hashIterations);
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}

一般的な開発過程ではMD 5で直接暗号化することはなく、塩値も追加しなければならない.この塩値は一般的に唯一である.
ログインの検証
public class UseMD5 {
    public static void main(String[]args){
        //1、  SecurityManager  ,    Ini       SecurityManager
        Factory factory =
                new IniSecurityManagerFactory("classpath:shiro-realm.ini");

        //2、  SecurityManager       SecurityUtils
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //3、  Subject      /      Token(     /  )
        Subject subject = SecurityUtils.getSubject();
        //         
        UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");

        try {
            //4、  ,     
            subject.login(token);
            //     user1 create  
            System.out.println(subject.isPermitted("user1:create:*"));
            //     role1  
            System.out.println(subject.hasRole("role1"));
        } catch (AuthenticationException e) {
            //5、      
            e.printStackTrace();
        }
        //6、  
        subject.logout();
    }
}

登録時に明文123456を伝え、検証時にMD 5に塩を加えたユーザー名で1024回暗号化した値を比較した.
開発では一般的にデータベースを使用してユーザー名を保存し、暗号化後のパスワードには塩の値が必要で、JdbcRealmに使用する必要があります.
まずsql文を実行してデータベースを作成し、データを挿入します.
drop database if exists shiro;
create database shiro;
use shiro;

create table users (
  id bigint auto_increment,
  username varchar(100),
  password varchar(100),
  password_salt varchar(100),
  constraint pk_users primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_users_username on users(username);

create table user_roles(
  id bigint auto_increment,
  username varchar(100),
  role_name varchar(100),
  constraint pk_user_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_user_roles on user_roles(username, role_name);

create table roles_permissions(
  id bigint auto_increment,
  role_name varchar(100),
  permission varchar(100),
  constraint pk_roles_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_roles_permissions on roles_permissions(role_name, permission);

insert into users(username, password, password_salt) values('jack', 'fc1709d0a95a6be30bc5926fdb7f22f4', 'jack');
insert into user_roles(username, role_name) values('jack', 'role1');
insert into user_roles(username, role_name) values('jack', 'role2');
insert into roles_permissions(role_name, permission) values('role1', 'user1:*');
insert into roles_permissions(role_name, permission) values('role1', 'user2:*');
insert into roles_permissions(role_name, permission) values('role2', 'user3:*');

shiro-jdbc.ini
[main]
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer

#   realm      securityManager.authorizer    (    setRealms  realms   authorizer,    Realm  permissionResolver rolePermissionResolver)
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.alibaba.druid.pool.DruidDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/shiro
dataSource.username=root
dataSource.password=root
jdbcRealm.dataSource=$dataSource
jdbcRealm.permissionsLookupEnabled=true

#       
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#    
credentialsMatcher.hashAlgorithmName=MD5
#    
credentialsMatcher.hashIterations=1024
jdbcRealm.credentialsMatcher=$credentialsMatcher

securityManager.realms=$jdbcRealm

これも以前より多くの暗号化マッチング器を構成しています
ログインの検証
public class UseJdbcMD5 {
    public static void main(String[]args){
        //1、  SecurityManager  ,    Ini       SecurityManager
        Factory factory =
                new IniSecurityManagerFactory("classpath:shiro-jdbc.ini");
        //2、  SecurityManager       SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //3、  Subject      /      Token(     /  )
        Subject subject = SecurityUtils.getSubject();
        //         
        UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");

        try {
            //4、  ,     
            subject.login(token);
            //     user1 create  
            System.out.println(subject.isPermitted("user1:create:*"));
            //     role1  
            System.out.println(subject.hasRole("role1"));
        } catch (AuthenticationException e) {
            //5、      
            e.printStackTrace();
        }
        //6、  
        subject.logout();
    }
}

ソースアドレス:https://github.com/jkgeekJack/shiro-learning/tree/master/chapter4