md5加密
今天学习了md5加密,这里简单分享一下!
第一步:创建一个maven工程,这里我用的是eclipse
第二步:导包,由于是maven工程,那么我们直接引用maven坐标
pom.xml配置文件如下:
<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.0</modelVersion>
<groupId>com.hd</groupId>
<artifactId>shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<version>3.0</version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port>8089</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding> <!-- 此行解决get方式提交乱码问题 -->
</configuration>
</plugin>
</plugins>
</build>
</project>
第三步:创建一个普通java类,继承抽象类如下,并且复写验证与授权这两个方法:
第四步:这里只做验证的加密
定义任意字符串,然后实例化md5Hash()对象,我们可以看到有好几个构造函数可以选,这里我们先用最简单的
完整的验证代码是这样的:
第五步:创建一个file文件,应该需要注意命名规则吧
ini配置信息如下:
注意关系:
具体代码一并附上:
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=1
b=com.hd.customerrealm.CustomerRealm
b.credentialsMatcher=$credentialsMatcher
securityManager.realms=$b
测试:
代码一并附上:
public static void main(String[] args) {
//解析ini文件
Factory<SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro-realm.ini");
//获取SecurityManager
SecurityManager securityManager = factory.getInstance();
//将SecurityManager配置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//获取subject实例对象
Subject subject = SecurityUtils.getSubject();
//获取token口令
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "hhh");
//模拟登录
subject.login(token);
//验证
boolean flag = subject.isAuthenticated();
System.out.println(flag);
}
那么,主方法运行:很抱歉异常了,它告诉我们找不到jar包...
加上maven坐标,保存一下...
代码附上:
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
再跑一下:
上面那一长串就是加密后的代码。
另外我们都知道md5是单向解密,无法逆转的。
以上.......完结....